Joel B Joel B - 3 months ago 9
R Question

How do I update the first n columns by adding each to a defined column in R

I have a data frame (df) below and I want to be able to add A to test and keep it called A, then B to test and keep that called B and then C to test and again keep that called C without hard-coding the column names (I will know exactly how many columns there are to add to test and the name of test so both of those aspects can be part of the code):

| A | B | C | test
------ | ------ | ------ | ------ | ------
area_1 | 0.870 | 0.435 | 0.968 | 0.679
area_2 | 0.456 | 0.259 | 0.906 | 0.467
area_3 | 0.298 | 0.256 | 0.457 | 0.768
area_4 | 0.994 | 0.987 | 0.365 | 0.765


Currently my code look like this (n is set to the number of columns I want to add to test) but it's leaving me with loads of NAs:

for (j in 1:n) {
df[,j] <- eval(df[,j] + df$test)
}

Answer

Why not simply do:

df[, -ncol(df)] <- df[, -ncol(df)] + df[[ncol(df)]]

Example

df <- data.frame(a = rep(1,5), b = rep(2, 5), c = rep(3,5))
#  a b c
#1 1 2 3
#2 1 2 3
#3 1 2 3
#4 1 2 3
#5 1 2 3

df[, -ncol(df)] <- df[, -ncol(df)] + df[[ncol(df)]]
#  a b c
#1 4 5 3
#2 4 5 3
#3 4 5 3
#4 4 5 3
#5 4 5 3
Comments