1

I'm new to R. In a data frame, I wanted to create a new column #21 that is equal to the sum of column #1 to #20,row by row.

I knew I could do

df$Col21<-df$Col1+df$Col2+.....+df$Col20

But is there a more concise expression?

Also, can I achieve this if using column names not numbers? Thanks!

2 Answers 2

3

There is rowSums:

df$Col21 = rowSums(df[,1:20]) 

should do the trick, and with names:

df$Col21 = rowSums(df[,paste("Col", 1:20, sep="")]) 

With leading zeros and 3 digits, try:

df$Col21 = rowSums(df[,sprintf("Col%03d", 1:20, sep="")]) 
Sign up to request clarification or add additional context in comments.

1 Comment

+1. For interactive use subset would also work: rowSums(subset(df, select = Col1:Col20)).
0

I find the dplyr functions for column selection very intuitive, like starts_with(), ends_with(), contains(), matches() and num_range():

df <- as.data.frame(replicate(20, runif(10)))
names(df) <- paste0("Col", 1:20)
library(dplyr)
# e.g.
summarise_each(df, funs(sum), starts_with("Col")) 
# or
rowSums(select(df, contains("8")))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.