[R] Multi-word column names in a data frame

Jim Lemon drj|m|emon @end|ng |rom gm@||@com
Wed Sep 5 06:22:44 CEST 2018


Hi Philip,
This may work:

library(dplyr)
`RefDate` <- as.Date(c("2010-11-1","2010-12-01","2011-01-01"))
`Number of vegetables` <- c(14,23,45)
`Number of people` <- c(20,30,40)
MyData <- data.frame(RefDate,`Number_of_vegetables`,
 `Number_of_people`,check.names=FALSE)
MyVars <- c("Number of vegetables","Number of people")
My_Vars <- c("Number_of_vegetables","Number_of_people")
nnames<-length(MyVars)
for (i in 1:nnames) {
   g2 <- ggplot(MyData,aes(RefDate,eval(parse(text=My_Vars[i])))) +
geom_line() +
     labs(title = paste(MyVars[i]," adjusted",sep=""))
   g2
   ggsave(paste(A,".jpg",sep=""),g2,height=5,width=8,dpi=300)
}

Jim
On Wed, Sep 5, 2018 at 1:22 PM <philipsm using cpanel1.stormweb.net> wrote:
>
> I am having trouble working with column names in a data frame. My
> column names are multi-word text strings and I like it that way. I
> want to loop through the columns, plotting graphs for each one, and I
> want to use the column names in the chart labels and in the file names
> when I save the charts. Here is a simple reproducible example that
> does not work.
>
> library(dplyr)
> `RefDate` <- as.Date(c("2010-11-1","2010-12-01","2011-01-01"))
> `Number of vegetables` <- c(14,23,45)
> `Number of people` <- c(20,30,40)
> MyData <- data.frame(RefDate,`Number of vegetables`,`Number of
> people`,check.names=FALSE)
> MyVars <- c("Number of vegetables","Number of people")
> for (A in MyVars) {
>    g2 <- ggplot(MyData,aes(RefDate,eval(parse(text=A)))) + geom_line() +
>      labs(title = paste(A," adjusted",sep=""))
>    g2
>    ggsave(paste(A,".jpg",sep=""),g2,height=5,width=8,dpi=300)
> }
>
> Philip
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list