这是你想要的吗? zoo
+ dplyr
也检查这里
df %>%
group_by(groupid) %>%
mutate_all(funs(na.locf(., na.rm = FALSE, fromLast = FALSE)))%>%filter(row_number()==n())
# A tibble: 1 x 5
# Groups: groupid [1]
groupid col1 col2 col3 col4
<int> <int> <chr> <int> <int>
1 1 0 n 2 2
EDIT1
没有过滤器的link,会给整个回数据帧。
df %>%
group_by(groupid) %>%
mutate_all(funs(na.locf(., na.rm = FALSE, fromLast = FALSE)))
# A tibble: 2 x 5
# Groups: groupid [1]
groupid col1 col2 col3 col4
<int> <int> <chr> <int> <int>
1 1 0 n NA 2
2 1 0 n 2 2
filter
这里,只是片最后一个,na.locf
将进行先前未NA
值,这意味着你的小组最后一排是你想要的。
也建议使用@ thelatemail。你可以做到以下几点,给出相同的答案。
df %>% group_by(groupid) %>% summarise_all(funs(.[!is.na(.)][1]))
EDIT2
假设你有冲突,你要告诉他们所有。
df <- read.table(text="groupid col1 col2 col3 col4
1 0 n NA 2
1 1 NA 2 2",
header=TRUE,stringsAsFactors=FALSE)
df
groupid col1 col2 col3 col4
1 1 0 n NA 2
2 1 1(#)<NA> 2 2(#)
df %>%
group_by(groupid) %>%
summarise_all(funs(toString(unique(na.omit(.)))))#unique for duplicated like col4
groupid col1 col2 col3 col4
<int> <chr> <chr> <chr> <chr>
1 1 0, 1 n 2 2
来源
2017-07-19 21:57:52
Wen
对您有帮助吗? https://stackoverflow.com/a/42567254/496803甚至这一个 - https://stackoverflow.com/questions/33601267/merging-similar-rows-in-a-data-frame/33601491 – thelatemail
检查我的答案和我提供的链接 – Wen
哦,第二个链接可能工作,我会试一试 – MokeEire