如何更改要在 R 中使用字符串操作调用的变量的名称?
how to change the name of a variable to be called using string manipulation in R?
我正在尝试更改要在运行时在 r 中调用的变量的名称。
例如,dataframe trades_long_final 有很多列 "prob_choice1" 和 "prob_choice2", ... "prob_choiceN" 和 "col1", "col2", ... "colN".
我想即时更改每个值。
例如,
trades_long_final$"prob_choice1"[1] = 10 and
trades_long_final$"prob_choice2"[1] = 10
有效
但不是
trades_long_final$gsub("1","2","prob_choice1")[1] = 10
作为调用 trades_long_final$"prob_choice2"[1] 的一种方式,将 prob_choice1 中的 1 替换为 2,因为我收到错误
Error: attempt to apply non-function
我需要它来工作,因为我需要使用类似 trades_long_final$gsub("i","2","prob_choicei")[1]循环所有 i.
非常感谢您的帮助。肯定是不知道怎么用的命令...
除了使用$
,您还可以使用[
更改变量名称并在一行中赋值。
trades_long_final[,gsub("1","2","prob_choice1")][1] <- 10
但是,不清楚为什么需要这样做。简直
trades_long_final[1, "prob_choice2"] <- 10
会更容易。根据描述,“prob_choice2”已经是数据集中的一列。所以,这很混乱。
数据
set.seed(24)
trades_long_final <- data.frame(prob_choice1 =runif(10),
prob_choice2=rnorm(10), col1=rnorm(10,10), col2=rnorm(10,30))
正如 akrun 所说,方法是使用 [
所以我的方法是:
for (k in 1:numtrades){
trades_long_final[[paste("prob_choice", k, sep="")]] =
{some complex procedure...}
}
我正在尝试更改要在运行时在 r 中调用的变量的名称。
例如,dataframe trades_long_final 有很多列 "prob_choice1" 和 "prob_choice2", ... "prob_choiceN" 和 "col1", "col2", ... "colN".
我想即时更改每个值。
例如,
trades_long_final$"prob_choice1"[1] = 10 and
trades_long_final$"prob_choice2"[1] = 10
有效
但不是
trades_long_final$gsub("1","2","prob_choice1")[1] = 10
作为调用 trades_long_final$"prob_choice2"[1] 的一种方式,将 prob_choice1 中的 1 替换为 2,因为我收到错误
Error: attempt to apply non-function
我需要它来工作,因为我需要使用类似 trades_long_final$gsub("i","2","prob_choicei")[1]循环所有 i.
非常感谢您的帮助。肯定是不知道怎么用的命令...
除了使用$
,您还可以使用[
更改变量名称并在一行中赋值。
trades_long_final[,gsub("1","2","prob_choice1")][1] <- 10
但是,不清楚为什么需要这样做。简直
trades_long_final[1, "prob_choice2"] <- 10
会更容易。根据描述,“prob_choice2”已经是数据集中的一列。所以,这很混乱。
数据
set.seed(24)
trades_long_final <- data.frame(prob_choice1 =runif(10),
prob_choice2=rnorm(10), col1=rnorm(10,10), col2=rnorm(10,30))
正如 akrun 所说,方法是使用 [
所以我的方法是:
for (k in 1:numtrades){
trades_long_final[[paste("prob_choice", k, sep="")]] =
{some complex procedure...}
}