在R中循环重命名变量

时间:2016-04-26 09:08:42

标签: r plyr

我试图通过从循环中附加一个字符串来重命名几个变量:

df <- data.frame(net_low_mptc=1:3,   net_medium_mptc=4:6, net_high_mptc=7:9)
x<-c("low","medium","high")


for(lvl in x) { 
rename(df, c(sprintf("net_%s_mptc", lvl) = sprintf("bill_%s_F", lvl))) }

错误是由sprintf表达式引起的:

Error: unexpected '=' in:
"for(lvl in x) { 
rename(df, c(sprintf("net_%s_mptc", lvl) ="

2 个答案:

答案 0 :(得分:2)

修改

colnames(df) <- sub("net_", "bill_", colnames(df))
colnames(df) <- sub("_mptc", "_F", colnames(df))

colnames(df)
# [1] "bill_low_F"    "bill_medium_F" "bill_high_F"  

我猜这里,也许试试这个:

x <- c("low", "medium", "high")
colnames(df_1)[colnames(df_1) %in% paste0("bill_no_net_tdcv_", x)] <- 
  paste0("bill_tdcv_", x, "_F")

使用正则表达式解决方案可能会更好,请提供您的数据。

答案 1 :(得分:1)

我猜这是他/她想要做的事情:

library(plyr)

x <- c("low","medium","high")

for(lvl in x) { 
  df_1 <- rename(df_1, setNames(sprintf("bill_tdcv_%s_F", lvl), sprintf("bill_no_net_tdcv_%s", lvl)))
}