rowSums specific columns in dataframe

Scott Prevost

2019/03/25

For summing multiple rows in columns to create a new column without typing (col1 + col2 + col3 +….). It also addresses NA values and removes them.

# Approach 1

dt %<>%
  .[, newcol1 := rowSums(.SD, na.rm = TRUE),
    .SDcols = c("column_names")] %>% 
  .[, newcol2 := rowSums(.SD, na.rm = TRUE),
    .SDcols = 4:6]


# Approach 2

dt %<>%
  .[, newcol := Reduce(`+`, .SD),
    .SDcols = c("column_names")]

See this Stack Overflow post for the example.