0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Glad it worked. For future reference - consider accepting an answer that satisfies your needs best, it is generally the best way to express gratitude. [1]: meta.stackexchange.com/questions/126180/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.