简体   繁体   English

如何在R中使用字符串操作更改要调用的变量的名称?

[英]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. 我正在尝试更改要在r中调用的变量的名称。

For example, dataframe trades_long_final has many columns "prob_choice1" and "prob_choice2", ... "prob_choiceN" and "col1", "col2", ... "colN". 例如,dataframe trades_long_final有许多列“prob_choice1”和“prob_choice2”,......“prob_choiceN”和“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 作为一种方法来调用trades_long_final $“prob_choice2”[1]通过用1替换prob_choice1中的1,因为我得到了错误

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. 我需要这个工作,因为我需要在所有i的循环中使用诸如trades_long_final $ gsub(“i”,“2”,“prob_choicei”)[1]之类的东西循环遍历列。

Thank you so much for your help. 非常感谢你的帮助。 It must be a command I don't know how to use... 它必须是一个我不知道如何使用的命令......

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. 根据描述,“prob_choice2”已经是数据集中的一列。 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))

as akrun said, the way to do it was to use [ so that the way I did it was: 正如akrun所说,做到这一点的方法是使用[这样我做的方式是:

for (k in 1:numtrades){

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM