Home > Software design >  Add new columns to a dataframe containing sum of positive values in a row and sum of negative values
Add new columns to a dataframe containing sum of positive values in a row and sum of negative values

Time:12-10

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!

CodePudding user response:

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

CodePudding user response:

Using dplyr:

df %>%
  mutate(pos = rowSums(replace(.[-1],.[-1]<0,0)),
         neg = rowSums(replace(.[-1],.[-1]>0,0)))
  •  Tags:  
  • r
  • Related