Search code examples
rrowsum

In R. conditionally adding values where one of the variables has to be positive (using rowsums)


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!


Solution

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