r - 加入没有 NA 的字符串
问题描述
我想总结没有na的字符串。
它与 str_c 一起使用,如下例所示
代码
df <- tibble(x = c("ISSUE-1", "ISSUE-2", "ISSUE-3", "ISSUE-4"), ID = c("ID-1", "ID-1", "ID-2", "ID-2")) %>%
group_by(ID) %>%
summarise(IDissue = str_c(x, collapse = "; "))
输出
ID issueID
ID-1 ISSUE-1; ISSUE-2
ID-2 ISSUE-3; ISSUE-4
但是,当 str_c 列中有 NA 时,会将完整输出转换为 NA,如文档中所述: https ://stringr.tidyverse.org/reference/str_c.html
与大多数其他 R 函数一样,缺失值具有“传染性”:每当缺失值与另一个字符串组合时,结果总是会缺失。使用 str_replace_na() 将 NA 转换为“NA” 代码
df <- tibble(x = c("ISSUE-1", "ISSUE-2", "ISSUE-3", NA), ID = c("ID-1", "ID-1", "ID-2", "ID-2")) %>%
group_by(ID) %>%
summarise(IDissue = str_c(x, collapse = "; "))
输出
ID IDissue
ID-1 ISSUE-1; ISSUE-2
ID-2 NA
有没有办法获得输出?
ID IDissue
ID-1 ISSUE-1; ISSUE-2
ID-2 ISSUE-3
解决方案
更简单的方法是filter
在group_by
library(stringr)
library(dplyr)
tibble(x = c("ISSUE-1", "ISSUE-2", "ISSUE-3", NA),
ID = c("ID-1", "ID-1", "ID-2", "ID-2")) %>%
filter(!is.na(x)) %>%
group_by(ID) %>%
summarise(IDissue = str_c(x, collapse = "; "))
推荐阅读
- maven - 无法从 Google Cloud Storage 获取存储库
- python - 将日期时间数据框与周期数据框进行比较
- c# - 在选择索引更改的同时显示加载屏幕
- linux - 由于对 Nuget 的 SSL 身份验证,.NET Core 构建在 docker linux 容器中失败
- python - 减去按一列分组的列的平均值
- php - SimpleXMLElement 命名空间的问题
- android - 将启动画面修复为 portlait
- java - 使用 Jersey 对查询数组参数进行排序
- python - 将 Pyspark 作业从 Windows 驱动程序提交到 Ubuntu Spark 集群时出现问题
- javascript - 外部 JS 文件在 Angular 7 中工作,但在 8 中不工作