简体   繁体   中英

I need Column sum as sum12 is sum of 1st columns and sum34 is of column 3 and 4

col1 col2   col3    col4
1     4        1    4
2     4        2    5
4     5        3    6
5     6        5    7

I need column sum like

col1    col2    col3    col4    sum12   sum34
1         4       1       4       5       5
2         4       2       5       6       7
4         5       3       6       9       9
5         6       5       7       11      12

We can use transform

transform(df, sum12 = col1 + col2, sum34 = col3 + col4)

Or another option is

df[c("sum12", "sum34")] <- df[c(1,3)] + df[c(2,4)]
df
#   col1 col2 col3 col4 sum12 sum34
#1    1    4    1    4     5     5
#2    2    4    2    5     6     7
#3    4    5    3    6     9     9
#4    5    6    5    7    11    12

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