Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a row to a dataframe modifying only some columns

In order to prepare the data for plotting I need to add a new row to the data:

I have this dataframe:

df <- data.frame(
  test_id = c(1, 1, 1, 1),
  test_nr = c(1, 1, 1, 1),
  region = c("A", "B", "C", "D"),
  test_value = c(3, 1, 1, 2)
)

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2

I would like to add a row to this dataframe so the desired output should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  test_id test_nr region test_value
1       1       1      A       3.00
2       1       1      B       1.00
3       1       1      C       1.00
4       1       1      D       2.00
5       1       1   mean       1.75

As you can see: column 1 and column 2 are the same value, column 3 changed to ‘mean’ and column 4 is the mean of row1-4.

I have tried to use add_row from tibble package which gives an error:

library(dpylr)
library(tibble)

df %>% 
  mutate(mean1 = mean(test_value)) %>% 
  add_row(test_id = test_id[1], test_nr=test_nr[1],region="mean", test_value=mean(test_value))

Error in eval_tidy(xs[[j]], mask) : object 'test_id' not found

>Solution :

You could do

library(dplyr)

df %>%
  add_row(test_id = .$test_id[1], test_nr = .$test_nr[1], region = "mean", test_value = mean(.$test_value))
#>   test_id test_nr region test_value
#> 1       1       1      A       3.00
#> 2       1       1      B       1.00
#> 3       1       1      C       1.00
#> 4       1       1      D       2.00
#> 5       1       1   mean       1.75
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading