Hi,
You can either parse and eval the string you are making, as in:
eval( parse( text = paste("avg_",colname, " <- 0;",
sep='') ) )
Or you can do something like this:
df[[ paste( "avg_", colname, sep = "" ) ]] <- 0
Romain
Philipp Schmidt wrote:> Hi:
>
> I very recently started experimenting with R and am occasionally
> running into very basic problems that I can't seem to solve. If there
> is an R-newbies forum that is more appropriate for these kinds of
> questions, please direct me to it.
>
> I'd like to automatically add vectors to a dataframe. I am able to
> build command strings that would do what I want, but R is not
> executing them.
>
> A simplified example:
>
> # Add three vectors called avg_col1, avg_col2, avg_col3 to dataframe df
> for(colname in c("col1", "col2", "col3")){
> print(paste("df$avg_",colname, " <- 0;",
sep='')) # Just using this
> to make sure the command is correct
> paste("avg_",colname, " <- 0;", sep='') #
Does nothing
> }
>
> Output:
>
> [1] "df$avg_col1 <- 0;"
> [1] "df$avg_col2 <- 0;"
> [1] "df$avg_col3 <- 0;"
>
> Thanks for your help!
>
> Best - P
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>
>
>
--
Romain Francois
Independent R Consultant
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr