Home > database >  R : Change name of variable using for loop
R : Change name of variable using for loop

Time:10-30

I have a data, and vectors conatin name of variables, from these vectorsi calculate the sum of variables contained in the vector and i want to put the result in a new variables that have diffrent names

let say i have three vectors

>data

Name      A    B    C    D    E
r1        1    5    12  21    15
r2        2    4     7  10     9
r3        5   15     6   9     6
r4        7    8     0   7    18

And i have these vectors that are generated using for loop that are in variable vec

V1 <- ("A","B","C")
V2 <- ("B","D")
V3 <- ("D","E")

Edit 1 : These vector are generated using for loop and i don't know the vectors that will be generated or the elemnts contained in these vector , here i'm giving just an example , i want to calculate the sum of variables in each vector and make the result in new variable in my data frame The issue is don't know how to give new name to variables created (that contains the sum of each vector)

 data$column[j]  <- rowSums(all_data_Second_program[,vec])
 j <- j 1

To obtain this result for example

Name      A    B    C   Column1      D     Column2    E      Column3
 r1       1    5   12     18         21      26      15         36 
 r2       2    4    7     13         10      14       9         19
 r3       5   15    6     26          9      24       6         15
 r4       7    8    0     15          7      15      18         25

But i didn't obtain this result

Please tell me if you need any more informations or clarifications Can you tell me please how to that

CodePudding user response:

Put the vectors in a list and then you can use rowSums in lapply -

list_vec <- list(c("A","B","C"), c("B","D"), c("D","E"))
new_cols <- paste0('Column', seq_along(list_vec))

data[new_cols] <- lapply(list_vec, function(x) rowSums(data[x]))
data

#  Name A  B  C  D  E Column1 Column2 Column3
#1   r1 1  5 12 21 15      18      26      36
#2   r2 2  4  7 10  9      13      14      19
#3   r3 5 15  6  9  6      26      24      15
#4   r4 7  8  0  7 18      15      15      25

CodePudding user response:

We may use a for loop

for(i in 1:3) {
    data[[paste0('Column', i)]] <- rowSums(data[get(paste0('V', i))],
          na.rm = TRUE)
}

-output

> data
  Name A  B  C  D  E Column1 Column2 Column3
1   r1 1  5 12 21 15      18      26      36
2   r2 2  4  7 10  9      13      14      19
3   r3 5 15  6  9  6      26      24      15
4   r4 7  8  0  7 18      15      15      25
  • Related