I have a tibble like Table1
, and I want to group some columns by the sum of their values for every row, creating a new column with the results and replacing the summed columns, like Table2
.
Table1
| Col_A | INTER | Col_B | Col_C | Col_D |
| ----- | ------- | ----- | ----- | ----- |
| 1 | [5-15) | 2 | 4 | 2 |
| 1 | [15-25) | 1 | 3 | 6 |
| 1 | [25-35) | 1 | 1 | 2 |
In this example I'd sum values from Col_B
and Col_D
, saving the results in Col_E
.
Table2
| Col_A | INTER | Col_C | Col_E |
| --- | --- | --- | --- |
| 1 | [5-15) | 4 | 4 |
| 1 | [15-25) | 3 | 7 |
| 1 | [25-35) | 1 | 3 |
In my real data I have several columns (numeric variables) and they have NAs.
I tried:
Table2 <- Table1 %>% mutate(Col_E = rowSums(across(c(Col_B, Col_D))))
I got this error:
Error: Problem with
mutate()
columnCol_E
.
iCol_E = rowSums(...)
.
x Must subset columns with a valid subscript vector.
x Subscript has the wrong typelogical
. i It must be numeric or character. i The error occurred in group 1: Col_A = 1, INTER = "[5,15)".
Combining some of the input from comments before, adding a reprex with slightly modified data to address NA removal as well as examples for tidy column selection and how to pre-specify the name of the new column (useful, if you have a couple of column groups you want to aggregate and e.g. keep everything in a list to iterate over).
Here, I remove the columns that where aggregated in the last step using select(- ...), but you may also want to look into transmute(), if you are interested in keeping only the new column, but from what I read, this is not the case here.
Created on 2023-11-14 with reprex v2.0.2