Joel B
Joel B

Reputation: 103

summing columns in a data frame based on the values stored within another data frame in R

I want to summarise a group of columns from df1

df1
  | A      | B      | C      | D
  | ------ | ------ | ------ | ------
1 | 0.870  | 0.435  | 0.968  | 0.679
2 | 0.456  | 0.259  | 0.906  | 0.467
3 | 0.298  | 0.256  | 0.457  | 0.768
4 | 0.994  | 0.987  | 0.365  | 0.765

if their column names appear as values within a column called TEST within df2

df2
  | test   |  
  | ------ | 
1 | A      | 
2 | B      | 

I've tried to use the followign code but I get the error below that

columns.to.add <- unique(df2$test)
df2$test <- colSums(columns.to.add)

Error in base::colSums(x, na.rm = na.rm, dims = dims, ...) : 'x' must be an array of at least two dimensions

Upvotes: 0

Views: 69

Answers (1)

jogo
jogo

Reputation: 12559

$ will not work in your case. You have to use indexing by column names:

colSums(df1[, df2$test])

Upvotes: 1

Related Questions