Quantcast

How to create data frame column name in a function

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

How to create data frame column name in a function

pvshankar
This post has NOT been accepted by the mailing list yet.
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
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

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

Rui Barradas
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
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

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

pvshankar
Thank you. It worked beautifully :)
Loading...