r - 跨列取消嵌套字符串组,但将它们保留在 R 中的原始行中
问题描述
我正在尝试找到一种方法来取消跨列的字符串组,但将所有字符串保留在原始行中。从中获取示例数据集starwars
,dplyr
因为它与我的数据集具有相似的结构。
数据集starwars
有 3 个嵌套列films
, vehicles
, starships
。常见的方法是这样做,unnest_longer
因此我们将字符串组取消嵌套为多行 - 每行包含一个字符串。但是,我更愿意将所有未分组的字符串保留在原始行中。
另一种方法是使用rowwise()
and mutate
with paste
。这可行,但我的数据集有 15 个嵌套列,所以我必须输入 15 行 mutate 和粘贴。这有点乏味。
df <- dplyr::starwars %>%
rowwise() %>%
mutate(films = paste(films, collapse=', '),
vehicles = paste(vehicles, collapse=', '),
starships = paste(starships, collapse=', '))
我目前的想法是想出一个包装函数,也许我可以purrr
大规模地完成它。但是我糟糕的函数编写不起作用 - 也许我对 dplyr 引擎盖不太熟悉。
ungroup_string <- function(data, x){
a <- rowwise(data)
a %>% mutate(x = paste(x, collapse=','))
}
有什么办法可以跨多列取消组合字符串?
解决方案
您可以使用across
:
library(dplyr)
starwars %>%
select(name, films, vehicles, starships) %>%
rowwise() %>%
mutate(across(c(films,vehicles, starships), toString))
# name films vehicles starships
# <chr> <chr> <chr> <chr>
# 1 Luke Skyw… The Empire Strikes Back, Revenge of… "Snowspeeder, I… "X-wing, Imperial shuttle"
# 2 C-3PO The Empire Strikes Back, Attack of … "" ""
# 3 R2-D2 The Empire Strikes Back, Attack of … "" ""
# 4 Darth Vad… The Empire Strikes Back, Revenge of… "" "TIE Advanced x1"
# 5 Leia Orga… The Empire Strikes Back, Revenge of… "Imperial Speed… ""
# 6 Owen Lars Attack of the Clones, Revenge of th… "" ""
# 7 Beru Whit… Attack of the Clones, Revenge of th… "" ""
# 8 R5-D4 A New Hope "" ""
# 9 Biggs Dar… A New Hope "" "X-wing"
#10 Obi-Wan K… The Empire Strikes Back, Attack of … "Tribubble bong… "Jedi starfighter, Trade Federation c…
# … with 77 more rows
across
接受 tidy-select 变量。因此,您不必一一指定 15 列中的每一列。您可以按位置1:15
、范围col1:col15
或名称中的某些模式选择列名称starts_with('col')
。
推荐阅读
- c - C - 使用 getchar() 只读取一个字符
- javascript - 将 React-Spring 示例转换为样式化组件
- java - 原生 Android 前台定位服务崩溃 Flutter 应用
- openpyxl - 使用 openpyxl(版本 2.4.1)读取 excel 文件时出现错误
- angular - 从依赖网络的 Web 应用程序到独立于网络的 Web 应用程序
- while-loop - 在 SAP Hana Sql 过程中,while 循环将结束
- python - 如何从头创建和使用新元素以对 Word 文档表中的单元格进行着色
- mysql - 可以将 MATCH AGAINST 与 COALESCE 一起使用吗?
- powershell - 使用 Powershell 将字符串转换为特定时区的 DateTime 对象
- javascript - 角度如何从可观察订阅的结果中设置组件变量