Home > Blockchain >  mutate columns with dynamic names using for loop in R
mutate columns with dynamic names using for loop in R

Time:01-19

I'm writing a For-loopto mutate columns k_et'm' with dynamic names. k_et did not exist before. b001 b002 b003 ... b012 are 12 variables that are already in the dataframe.

b001 b002 b003 ... b012
-2    2    0   ...   1
-1    1    0   ...   0
 1    1   -1   ...  -2

I put them into a dataframe called b. (But it causes that I generate them again. I feel like it's redundant but cannot think of any other way.)

month <- c("001","002","003","004","005","006","007","008","009","010","011","012")

for(m in 1:length(month)) {
  b <- c(paste0("b",m))
  k_et[m] <- paste0("k_et",month[m]) 
  df[,k_et[m]] <- ifelse(b[m]==1, 1, 0)
}

I expect to see:

b001 b002 b003 ... k_et001 k_et002 k_et003
-2    2    0   ...   0       0        0    
-1    1    0   ...   0       1        0
 1    1   -1   ...   1       1        0

However, all my k_et results are 0. What is the problem?

CodePudding user response:

You don't need a loop for this. Do it all at once.

## get the values. ifelse() keeps the dimensions
results = ifelse(df == 1, 1, 0)
## fix the names, replacing "b" with "k_et"
colnames(results) = sub(pattern = "b", replacement = "k_et", x = colnames(results))
## stick them together
df = cbind(df, results)
  •  Tags:  
  • Related