MikeMEiL
MikeMEiL

Reputation: 13

Sum columns of data frame when condition is met

I would like to make a new column that would be the sum of only positive values in existing columns. So in column TotalImportSE3 I would like to obtain sum of of columns SE3-NO1, SE3-DK1, SE3-FI, SE3-SE4 only of positive values, if noone of them are positive sum should be 0.

      SE3 - NO1 SE3 - DK1 SE3 - FI SE3 - SE2 SE3 - SE4 TotalImportSE3
 47      1114       666     -225      2716     -3784             NA
 48      1009       671     -151      1491     -2943             NA
 54      1057       711    -1062      1658     -2201             NA
 55      1077       711    -1213      3492     -3015             NA
 94       772       414     -501      2904     -2262             NA
 95      -786      -314     -407     -2368     -2005             NA

Output should look like:

      SE3 - NO1 SE3 - DK1 SE3 - FI SE3 - SE2 SE3 - SE4 TotalImportSE3
 47      1114       666     -225      2716     -3784             4496
 48      1009       671     -151      1491     -2943             3171
 54      1057       711    -1062      1658     -2201             3426
 55      1077       711    -1213      3492     -3015             5280
 94       772       414     -501      2904     -2262             4090
 95      -786      -314     -407     -2368     -2005             0

So far my effort:

df1 <- df$`SE3 - NO1`[which(Data$`SE3 - NO1`>0)]
df2 <- df$`SE3 - DK1`[which(Data$`SE3 - DK1`>0)]

But it does create two vectors of different lenghts, so it messes up completely.

Upvotes: 0

Views: 120

Answers (1)

Zeinab Ghaffarnasab
Zeinab Ghaffarnasab

Reputation: 818

you can try this:

 df$TotalImportSE3=rowSums(df*(df>0))
  • df is name of your dataframe

Upvotes: 3

Related Questions