Re: [Rd] How to create data frame column name in a function

From: Rui Barradas <ruipbarradas_at_sapo.pt>
Date: Thu, 03 May 2012 05:55:22 -0700 (PDT)

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.

______________________________________________
R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Thu 03 May 2012 - 12:57:40 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 05 May 2012 - 00:50:54 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive