Dplyr:如何按组查找第一个也不丢失的字符串? [英] Dplyr : how to find the first-non missing string by groups?

查看:88
本文介绍了Dplyr:如何按组查找第一个也不丢失的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下简单示例

group <-c('A','A','A','B','B','B','B')
names<- c(NA,'fred',NA,'josh','josh',NA,NA)
data=data_frame(group,names)

> data
# A tibble: 7 × 2
  group names
  <chr> <chr>
1     A  <NA>
2     A  fred
3     A  <NA>
4     B  josh
5     B  josh
6     B  <NA>
7     B  <NA>

在这里,我想得到每个 名称中的第一个非缺失名称。我怎样才能做到这一点?以下使用 coalesce first 的解决方案失败。

Here, I would like to get, for each group the first non missing name in names. How can I do that? The solution below using coalesce and first fail.

data %>% group_by(group) %>% mutate(first_non_missing = first(names),
                                    first_non_missing_alt = coalesce(names)) %>% ungroup()

# A tibble: 7 × 4
  group names first_non_missing first_non_missing_alt
  <chr> <chr>             <chr>                 <chr>
1     A  <NA>              <NA>                  <NA>
2     A  fred              <NA>                  fred
3     A  <NA>              <NA>                  <NA>
4     B  josh              josh                  josh
5     B  josh              josh                  josh
6     B  <NA>              josh                  <NA>
7     B  <NA>              josh                  <NA>

确实,对于组 A ,<$对于所有三个观察结果,c $ c> first_non_missing 应该为 fred

Indeed, for group A, first_non_missing should be fred for all three observations..

很多谢谢!

推荐答案

摘要将为每个组给出一个条目,在这里,使用查找第一个未缺失的项其中

Summarise will give one entry per group, here, finding the first non-missing using which

data %>%
  group_by(group) %>%
  summarise(first_non_missing = names[which(!is.na(names))[1]])

给予

  group first_non_missing
  <chr>             <chr>
1     A              fred
2     B              josh

如果您仍然想要所有行,将总结替换为 mutate

If you still want all of the rows, replace summarise with mutate.

这篇关于Dplyr:如何按组查找第一个也不丢失的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆