Reputation: 14535
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
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