0

I have used the following code previously to add values of a row:

subset$EBIT <- rowSums(subset[c("rorresul", "resand", "rteinknc", 
                                            "rteinext", "rteinov")], na.rm = TRUE)

However, I would actually need to include the condition that "resand" should only be included if it is positive. The other values can be either positive or negative, it does not matter. I have used rowSums because otherwise my total ended up a missing value if one of the variables had a missing value in them.

If you need sample of data, here is some:

rorresul  resand  rteinknc  rteinext  rteinov
  40        30       2         2         2
  50        -40      5         5         5
  30         0       1         1         1

Super appreciative of any help! Thanks!

2 Answers2

2

I would just sum everything, and then subtract resand after:

library(dplyr)

df %>% 
  mutate(
    EBIT = rowSums(across(everything())),
    EBIT = ifelse(resand < 0, EBIT - resand, EBIT)
  )

#   rorresul resand rteinknc rteinext rteinov EBIT
# 1       40     30        2        2       2   76
# 2       50    -40        5        5       5   65
# 3       30      0        1        1       1   33

Here is the data:

df <- data.frame(
  rorresul = c(40, 50, 30),
  resand = c(30, -40, 0),
  rteinknc = c(2, 5, 1),
  rteinext = c(2, 5, 1),
  rteinov = c(2, 5, 1),
  stringsAsFactors = FALSE
)

Edit In case you have variables that shouldn't be included in the rowSums, then you can prespecify these:

sumVars <- c("rorresul", "resand", "rteinknc", "rteinext", "rteinov")

df %>% 
  mutate(
    EBIT = rowSums(across(all_of(sumVars))),
    EBIT = ifelse(resand < 0, EBIT - resand, EBIT)
  )
WilliamGram
  • 673
  • 3
  • 7
  • say I have more variables in the dataset and not only the ones in the sample above, should I then do `across(rorresul, resand, rteinknc, rteinext, rteinov)` instead? – coding_sailor Apr 03 '21 at 07:18
  • I appreciate the question, and updated my answer accordingly. Let me know if that works for you. – WilliamGram Apr 03 '21 at 07:22
1

You can use pmax to turn the negative values to 0 for resand and calculate rowSums.

cols <- c("rorresul", "resand", "rteinknc", "rteinext", "rteinov")
df$EBIT <- rowSums(transform(df, resand = pmax(resand, 0))[cols])
df
#  rorresul resand rteinknc rteinext rteinov EBIT
#1       40     30        2        2       2   76
#2       50    -40        5        5       5   65
#3       30      0        1        1       1   33
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213