I have faces DF with some incomplete and repetitive characteristics:
name <- c("A", "A", "B", "B", "B", "C", "D", "D")
age <- c(28,NA,NA,NA,NA,NA,53,NA)
birthplace <- c("city1",NA, "city2",NA,NA,NA,NA,NA)
value <- 100:107
df <- data.frame(name,age,birthplace,value)
name age birthplace value
1 A 28 city1 100
2 A NA <NA> 101
3 B NA city2 102
4 B NA <NA> 103
5 B NA <NA> 104
6 C NA <NA> 105
7 D 53 <NA> 106
8 D NA <NA> 107
Since the value is unique to the string. I want each line with detailed details to look like this:
name age birthplace value
1 A 28 city1 100
2 A 28 city1 101
3 B NA city2 102
4 B NA city2 103
5 B NA city2 104
6 C NA <NA> 105
7 D 53 <NA> 106
8 D 53 <NA> 107
I tried to use
library(zoo)
library(dplyr)
df <- df %>% group_by(name) %>% na.locf(na.rm=F)
But this is not very good. Any idea for implementing a function on a group?
source
share