Search code examples
rdataframevectorcalculated-columnsrowsum

R Creating new columns using vector contains name of variables


I have a data and a vector contain name of variables and i want to create new variable contain rowsum of variables in my vector, and i want the name of new variable ( sum of variables in my vector) to be concatenation of names of variables

for example i have this data

> 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 this vector

>Vec

"A" , "C" , "D"

the result i want is the sum of Variables A , C and D and the name of my variable is ACD

here's the result i want :

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

I tried this :

data <- cbind(data , as.data.frame(rowSums(data[,Vec]) ))

But i don't know how to create the name

Here's the result i got

 >data
    
       Name       A    B    C    D     E  rowSums(data[,Vec])
        r1        1    5    12  21    15    34
        r2        2    4     7  10     9    18
        r3        5   15     6   9     6    20
        r4        7    8     0   7    18    14

Not that i gave just a sample example to explain what i want to do

i want to do affectation of my old data to my new data ( that contains the new variable), like i did in my command above

edit 1 : in my real program , i don't know the elements ( name of my variables in my vector so i can not do data$ACD <- cbind(data , as.data.frame(rowSums(data[,Vec]) )) as suggested by Pax, in fact i have for loop that generate my vectors and each time i create variable to put the result i want ( sum of variable in my vector) so i don't know how to affect the name without knowing the elements of vectors

Please tell me if you need anymore clarifications or informations

Thank you


Solution

  • It's not a one line solution but you can set the name on the subsequent line:

    data <- data.frame(A = c(1, 2, 5, 7), 
                       B = c(5, 4, 15, 8), 
                       C = c(12, 7, 6, 0), 
                       D = c(21, 10, 9, 7), 
                       E = c(15, 9, 6, 18))
    Vec <- c("A" , "C" , "D")
    
    data <- cbind(data, rowSums(data[,Vec]))
    
    # Add name
    names(data)[ncol(data)] <- paste(Vec, collapse="")
    
    
    #   A  B  C  D  E ACD
    # 1 1  5 12 21 15  34
    # 2 2  4  7 10  9  19
    # 3 5 15  6  9  6  20
    # 4 7  8  0  7 18  14