I'm web-scraping a data frame that is typically 1 column and 8 rows. Sometimes the data frame is missing one observation (row 6). As such, my variables get out of order while scraping (7 becomes 6, 8 becomes 7) and cascades to cause other problems.
I have a solution to this problem when row 6 is missing. I'm using add_row to add a placeholder row that ends up with a value of 'NA' (exactly what I want).
#Data frame with missing value
value <- c(10, 43, 67, 89, 05, 28, 99)
df <- data.frame(value)
#Solving the problem
df2<-df %>% add_row(value=NA,.before=6)
My question is - is there a way to add_row conditionally? If there is less than 8 rows, add the missing row, or else do nothing?
Thanks.
CodePudding user response:
This should do the job
if(length(df$value) != 8){
df[0:length(df$value) 1,"value"] <- c(df$value[1:5], NA, df$value[6:length(df$value)])
}
CodePudding user response:
Here's one way -
value <- c(10, 43, 67, 89, 05, 28, 99)
if(length(value) == 7) {
value <- append(value, NA_integer_, after = 5)
}
df <- data.frame(value)
One way with dplyr
-
tibble(value) %>%
{if(nrow(.) == 7) add_row(., value = NA_integer_, .after = 5) else .}
# A tibble: 8 × 1
value
<dbl>
1 10
2 43
3 67
4 89
5 5
6 NA
7 28
8 99