简体   繁体   中英

adding values in certain columns of a data frame in R

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!

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="")]) 

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")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM