James L.
James L.

Reputation: 14535

Replace column with Summation value in R

Given a data frame in R

#   ID x1 x2 x3 x4
# 1  1  1  1  1  1
# 2  1  1  2  3  4
# 3  2  1  5  6  7
# 4  3  1  8  9  2

I want to replace the columns with their summation value

#   ID x1 x2 x3 x4
# 1  1  4 16 19 14

However, trying to set the sum directly replaces all the values with the sum:

for (nm in names(df)) {
  df[nm] = sum(df[nm])
}

#   ID x1 x2 x3 x4
# 1  1  4 16 19 14
# 1  2  4 16 19 14
# 1  3  4 16 19 14
# 1  4  4 16 19 14

Upvotes: 0

Views: 280

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48241

I believe the ID column is no longer needed. Then simply

colSums(df[, -1])
# x1 x2 x3 x4 
#  4 16 19 14 

Upvotes: 1

Related Questions