jeudi 12 mai 2022

Create new rows that are conditional on earlier rows

I want to create output_df, which adds two rows to the bottom.

The new rows are:

  • assigned NA for column z, and
  • percentage is calculated such that sum(output_df$x == "Y" & output_df$y == "A") == 1 and sum(output_df$x == "N" & output_df$y == "B") == 1
original_df <- data.frame(x = c("Y","N","Y","N"),
                          y = c("A","B","A","B"),
                          z = c("a","b","c","d"),
                          percentage = c(0.1, 0.2, 0.5, 0.5)) 

output_df <- data.frame(x = c("Y","N","Y","N","Y","N"),
                        y = c("A","B","A","B","A","B"),
                        z = c("a","b","c","d",NA , NA),
                        percentage = c(0.1, 0.2, 0.5, 0.5, 0.4, 0.3)) 

For context, my intent is to use output_df to feed into the sample function, where replace = T.




Aucun commentaire:

Enregistrer un commentaire