Replace part of expression with value from variable

I would like to write an expression in R where I can change part of it depending on some other variable. For example, let's say that I want to create many new columns in my dataframe using the following basic expression:

MyDataFrame$ColumnNumber1 <- 33

      

If I wanted to create many of these I could just print them explicitly

MyDataFrame$ColumnNumber2 <- 52
MyDataFrame$ColumnNumber3 <- 12
...

      

etc. However, it would be impractical if I had a lot of them. So I would like to have a way to replace part of the expression with something that is generated via a variable. Suppose, for example, say that there is an operator Input()

who will do this. Then I could write a function that looks like this:

for(i in 1:1000)
{
    MyDataFrame$ColumnNumberInput(i) <- 32*i
}

      

where the part Input(i)

will be replaced with whatever number the counter was on at the moment, which in turn will generate an expression.

Now I can do it using:

eval(parse(text=paste("MyDataFrame$","Column","Number","1","<- 32*i",sep="")))

      

but it becomes impossible to use if the expression is too complex, long, or has other things like this nested inside it.

+3


source to share


1 answer


Use [[]]

:

for(i in 1:1000)
{
    MyDataFrame[[i]] <- 32*i
} 

      

[[]]

is the software equivalent $

.

Then you can refer to the data structure as:

MyDataFrame[[14]] <- MyDataObjFourteen
MyDataFrame$14
MyDataFrame[[14]]

      



You can also use strings like:

MyDataFrame[["SomeString"]] <- 32
MyDataFrame$SomeString
# 32

      

EDIT 1:

To do something like this, in a more general way, try:

assign("someArbitraryString", 3)
someArbitraryString
# 3
as.name(someArbitraryString)

      

+2


source







All Articles