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

Adding rows depending on condition

I need a little help with a very simple question:

Let’s say I have this data frame:

data_new <- data.frame(section = c("1", "4", "5","6"),
                       density = c("0.2", "0.7", "0.8", "0.2"))
> data_new
  section density
1       1     0.2
2       4     0.7
3       5     0.8
4       6     0.2

I need to add rows because the full table is based on 6 sections, but only have data on 4. This means that in this case I have to add 2 rows (sections 2 and 3) with density 0 so I have:

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

> data_desired
  section density
1       1     0.2
2       4     0.7
3       5     0.8
4       6     0.2
5       2       0
6       3       0

The point is that the combination of 0 density rows may vary. In this case sections 3 and 4 were empty, but next time it may be that no section has density 0 or that I have to add 5 sections, etc. It can vary a lot, from 1 section with data to all sections with data.

I’m sure there is an elegant way to add to my pipe to ad the rows I need and that is case specific. Thanks a lot for your help!!

>Solution :

Another option using rows_update:

library(dplyr)
#create zero density dataframe

n<-6
data_zero <- data.frame(section = as.character(c(1:n)),
                       density = as.character(rep(0,n)))

data_new <- data.frame(section = c("1", "4", "5","6"),
                       density = c("0.2", "0.7", "0.8", "0.2"))

rows_update(data_zero ,data_new)
  section density
1       1     0.2
2       2       0
3       3       0
4       4     0.7
5       5     0.8
6       6     0.2

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