newmathwhodis
newmathwhodis

Reputation: 3289

how to change the name of a variable to be called using string manipulation in R?

I am trying to change the name of a variable to be called in r on the fly.

For example, dataframe trades_long_final has many columns "prob_choice1" and "prob_choice2", ... "prob_choiceN" and "col1", "col2", ... "colN".

I want to change the value of each on the fly.

For example,

trades_long_final$"prob_choice1"[1] = 10 and 
trades_long_final$"prob_choice2"[1] = 10 

works

but not

trades_long_final$gsub("1","2","prob_choice1")[1] = 10 

as a way to call trades_long_final$"prob_choice2"[1] by substituting the 1 in prob_choice1 with a 2 because I get the error

Error: attempt to apply non-function

I need this to work because I need to loop over the columns using something like trades_long_final$gsub("i","2","prob_choicei")[1] in a loop for all i.

Thank you so much for your help. It must be a command I don't know how to use...

Upvotes: 1

Views: 178

Answers (2)

newmathwhodis
newmathwhodis

Reputation: 3289

as akrun said, the way to do it was to use [ so that the way I did it was:

for (k in 1:numtrades){

        trades_long_final[[paste("prob_choice", k, sep="")]] = 
    {some complex procedure...}

}

Upvotes: 0

akrun
akrun

Reputation: 887611

Instead of using $, you can use [ to change the variable name and assign the value in one line.

 trades_long_final[,gsub("1","2","prob_choice1")][1] <- 10 

But, it is not clear why you need to do this. Simply

 trades_long_final[1, "prob_choice2"] <- 10

would be easier. From the description, "prob_choice2" is already a column in the dataset. So, it is confusing.

data

set.seed(24)
trades_long_final <- data.frame(prob_choice1 =runif(10), 
    prob_choice2=rnorm(10), col1=rnorm(10,10), col2=rnorm(10,30))

Upvotes: 3

Related Questions