Column names contain periods in which spaces should be

In the graph generated by ggplot, each label along the x axis represents a line, that is, a β€œwork in 1990." However, the generated graph has a period between each word. In other words, the specified string is shown as "the.product.in.1990"

How can I provide the above "." not added?

The following code is what I used to add a row for each point along the x axis

last_plot()+scale_x_discrete(limits=ddata$labels$text) 

Code example:

 library(ggdendro) x <- read.csv("test.csv",header=TRUE) d <- as.dist(x,diag=FALSE,upper=FALSE) hc <- hclust(d,"ave") dhc <- as.dendrogram(hc) ddata <- dendro_data(dhc,type="rectangle") ggplot(segment(ddata)) + geom_segment(aes(x=x0,y=y0,xend=x1,yend=y1)) last_plot() + scale_x_discrete(limits=ddata$labels$text) 

each line of ddata$labels$text represents a line, for example, "product in 1990." I would like to keep the same format in the generated chart, and not in "the.product.in.1990"

+4
source share
1 answer

The problem arises because you are trying to read data with column names that contain spaces.

When you read this data with read.csv , these column names are converted to syntactically valid R names. Here is an example illustrating the problems:

 some.file <- ' "Col heading A", "Col heading B" A, 1 B, 2 C, 3 ' 

Read it with read.csv default settings:

 > x1 <- read.csv(text=some.file) > x1 Col.heading.A Col.heading.B 1 A 1 2 B 2 3 C 3 4 NA > names(x1) [1] "Col.heading.A" "Col.heading.B" 

To avoid this, use the argument check.names=FALSE :

 > x2 <- read.csv(text=some.file, check.names=FALSE) > x2 Col heading A Col heading B 1 A 1 2 B 2 3 C 3 4 NA > names(x2) [1] "Col heading A" "Col heading B" 

Now the remaining problem is that the column name cannot contain spaces. Therefore, to refer to these columns, you need to wrap the column name in backlinks:

 > x2$`Col heading A` [1] ABC Levels: ABC 

For more information, see ?read.csv and, in particular, information for check.names .

There is also some information about backticks in ?Quotes

+15
source

Source: https://habr.com/ru/post/1385369/


All Articles