I am trying to add two specific values in R. I am new to R and so far I have used colSums and it does give me the right values. However, I was wondering if there was a way to add specific cells and then add as them as row to the dataframe. In this case, I would like to add the last two columns.
Here's sample data:
col1 | col2 | col3 |
---|---|---|
3 | 7 | a |
2 | 4 | b |
1 | 5 | c |
Desired output:
col1 | col2 | col3 |
---|---|---|
3 | 7 | a |
3 | 9 | b&c |
CodePudding user response:
Admittingly, this is not pretty as it mixes tidyverse
and base R. But, we can use a custom function, since we are dealing with columns of different classes, i.e colSums
will not work because "a" "b"
is not "ab"
.
library(dplyr)
df <-
tribble(
~col1, ~col2, ~col3,
3, 7, "a",
2, 4, "b",
1, 5, "c"
)
f <- function(df) {
replace <- df %>%
tail(2) %>%
summarise(
col1 = sum(col1),
col2 = sum(col2),
col3 = paste0(col3, collapse = "&")
)
bind_rows(
df %>% head(-2),
replace
)
}
df %>%
f()
#> # A tibble: 2 x 3
#> col1 col2 col3
#> <dbl> <dbl> <chr>
#> 1 3 7 a
#> 2 3 9 b&c
CodePudding user response:
DF <- DF %>%
recode(col3, b = "b&c", c = "b&c")
group_by(col3) %
summarise(col1 = sum(col1), col2 = sum(col2)) %
ungroup()