[R] using sapply to apply function to some columns of a dataframe

mwestphal at worldbank.org mwestphal at worldbank.org
Tue Feb 17 22:42:20 CET 2009


I would like to sum every x columns of a dataframe for each row.  For instance,
if x is 10, then for dataframe df, this function will sum the first ten elements
together and then the next ten:

sapply(list(colnames(df)[1:10], colnames(df)[11:20]),function(x)apply( df[,x],
1, sum))

If the number of columns is quite large (1000's), then manually entering the
list above is not practical.  Any suggestions?

I would also like to do a variant of the above, where I sum every nth element.



Michael I. Westphal, PhD
Africa Region Water Resources (AFTWR)
South Asia Region Sustainable Development (SASSD)
World Development Report 2010: "Development in a Changing Climate"
Room J6-007 (mail stop: J6-603)
Tel: 202.473.1217
The World Bank
1818  H St NW, Washington DC 20433, USA

More information about the R-help mailing list