-2

I'm trying to rename several variables by attaching a string from a loop:

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))) }

The error is caused by the sprintf expression:

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

2 Answers2

2

Edit:

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"  

I am guessing here, maybe try this:

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

You might be better off with regex solution, please provide your data.

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • 1
    you might get some unexpected result there if the colnames are not in the same order than x (e.g. you're risking replacing something with `high` by something with `low`) – Cath Apr 26 '16 at 09:38
  • 1
    done ;-) and probably `colnames(df) <- sub(paste0("net_(", paste(x, collapse="|"), ")_mptc"), "bill_\\1_F", colnames(df))` would do it – Cath Apr 26 '16 at 09:54
1

I'm guessing this is what he/she is trying to do:

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)))
}
hatmatrix
  • 42,883
  • 45
  • 137
  • 231