简体   繁体   中英

Add new columns to a dataframe containing sum of positive values in a row and sum of negative values in a row - R

I have a dataframe df which looks like this

ID  A  B  C  D  E  F  G 
1   0  0  1 -1  1  0  0
2   1  1  1  0  0  0  0
3   -1 0  1  0  -1 -1 0 
.
. 
. 

I want to add two column at the end of each row showing the sum of positive values and the sum of negative values so df would look like this

ID  A  B  C  D  E  F  G pos neg
1   0  0  1 -1  1  0  0  2   -1
2   1  1  1  0  0  0  0  3    0
3   -1 0  1  0  -1 -1 0  1    -3 
.
. 
. 

I can't figure out how to do this. I have tried the following which turns the df into a list

df$neg <- rowSums(df < 0)

I have also tried the following which throws up an error message:
Error in df[, c("A", "B", "C", : subscript out of bounds

df$neg <- rowSums(df[, c("A", "B", "C", "D", "E", "F", "G")] < 0)

Any help would be really appreciated, thanks!

We can try this

cbind(
  df,
  pos = rowSums(df[-1] * (df[-1] > 0)),
  neg = rowSums(df[-1] * (df[-1] < 0))
)

which gives

  ID  A B C  D  E  F G pos neg
1  1  0 0 1 -1  1  0 0   2  -1
2  2  1 1 1  0  0  0 0   3   0
3  3 -1 0 1  0 -1 -1 0   1  -3

Data

> dput(df)
structure(list(ID = 1:3, A = c(0L, 1L, -1L), B = c(0L, 1L, 0L
), C = c(1L, 1L, 1L), D = c(-1L, 0L, 0L), E = 1:-1, F = c(0L,
0L, -1L), G = c(0L, 0L, 0L)), class = "data.frame", row.names = c(NA,
-3L))

Using dplyr :

df %>%
  mutate(pos = rowSums(replace(.[-1],.[-1]<0,0)),
         neg = rowSums(replace(.[-1],.[-1]>0,0)))

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