Skip to content

Summing Select Columns of a Data Frame?

4 messages · Julia Zhou, Jorge Ivan Velez, Stephan Kolassa

#
Hi,

I would like to operate on certain columns in a dataframe, but not
others. My data looks like this:

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

I want to create a new column named x4 that is the sum of x1 and x2,
but NOT x3. I looked at colSums and apply, but those functions seem to
use all the columns in a dataframe. How do I only use select columns?

If it helps, in Stata this would be gen x4 = x1 + x2.

Thanks!
#
Hi Julia,

or you can use colSums on an appropriate sub-data.frame:

colSums(dataset[,c(1,2)])

HTH,
Stephan


Jorge Ivan Velez schrieb: