Rui Barradas
2012-May-03 12:55 UTC
[Rd] How to create data frame column name in a function
Hello, pvshankar wrote> > Hello all, > > I have a data frame with column names s1, s2, s3....s11 > > I have a function that gets two parameters, one is used as a subscript for > the column names and another is used as an index into the chosen column. > > For example: > > my_func <- function(subscr, index) > { > if (subscr == 1) > { > df$s1[index] <- some value > } > } > > The problem is, I do not want to create a bunch of if statements (one for > each 1:11 column names)). > Instead, I want to "create" the column name in run time based on subscr > value. > > I tried eval(as.name(paste("df$s",subscr,sep="")))[index] <- some value > > and it complains that object df$s1 is not found. > > Could someone please help me with this? > (Needless to say, I have just started programing in R) > > Thanks, > Shankar >Instead of operator '$' use function`[<-` with the right indexes. cname <- paste("s", subscr, sep="") DF[index, cname] <- value See ?"[<-.data.frame" (And df is the name of an R function, use something else, it can be confusing.) Hope this helps, Rui Barradas -- View this message in context: http://r.789695.n4.nabble.com/How-to-create-data-frame-column-name-in-a-function-tp4605358p4605939.html Sent from the R devel mailing list archive at Nabble.com.
Thank you. It worked beautifully :) -- View this message in context: http://r.789695.n4.nabble.com/How-to-create-data-frame-column-name-in-a-function-tp4605358p4608663.html Sent from the R devel mailing list archive at Nabble.com.