I would like to write an expression in R where I can modify some part of it depending on some other variable. For example, let's say that I want to create a lot of new columns in my data frame using the following basic expression:
MyDataFrame$ColumnNumber1 <- 33
If I wanted to create a lot of these, I could just type them out explicitly
MyDataFrame$ColumnNumber2 <- 52
MyDataFrame$ColumnNumber3 <- 12
...
and so on. However, this would be impractical if I have to many of them. Therefore, I'd like to have some way of replacing a part of the expression with something that's generated through a variable. Let's for example say that there was an operator Input() that would do this. Then I could write a function looking like this:
for(i in 1:1000)
{
MyDataFrame$ColumnNumberInput(i) <- 32*i
}
where the Input(i) part would be replaced with whatever number the counter were at at the moment, which in turn would generate an expression.
I now that I can do this by using:
eval(parse(text=paste("MyDataFrame$","Column","Number","1","<- 32*i",sep="")))
but this gets impossible to use if the expression is too complicated, long, or have other things like this nested inside of it.
do.call(cbind, list(df, lapply(1:10, function(u) setNames(data.frame(u*32),u))))MyDataFrame[, paste0("ColumnNumber", i) <- 52? It's not obvious what exactly you are trying to achieve. There might be a better approach.[[]]operator, which is what I think @Speldose wants here, is helpful. Literate programming, where ease of maintenance and readability are given priority over efficiency, come to mind. That said, this approach does lend itself to "speaking R with a C accent," and thus should be used with caution. If you don't need to prioritize readability, consider the approach suggested by @ColonelBeauvel.xno matter where it's placed.