r - 有条件地将字符串连接到多行
问题描述
我从包含多行字符串的 PDF 中提取了多个表。我使用了 tabulizer 包中的 extract_table() 函数,唯一的问题是字符串作为单独的行导入。
例如
action <- c(1, NA, NA, 2, NA, 3, NA, NA, NA, 4, NA)
description <- c("a", "b", "c", "a", "b", "a", "b", "c", "d", "a", "b")
data.frame(action, description)
action description
1 1 a
2 NA b
3 NA c
4 2 a
5 NA b
6 3 a
7 NA b
8 NA c
9 NA d
10 4 a
11 NA b
我想连接字符串,使它们显示为相同的元素,例如:
action description
1 1 a b c
2 2 a b
3 3 a b c d
4 4 a b
希望这是有道理的,感谢任何帮助!
解决方案
tidyverse
方法是到具有先前非 NA 值fill
的列然后和在一起。action
group_by
Action
paste
description
library(tidyverse)
df %>%
fill(action) %>%
group_by(action) %>%
summarise(description = paste(description, collapse = " "))
# action description
# <dbl> <chr>
#1 1. a b c
#2 2. a b
#3 3. a b c d
#4 4. a b
推荐阅读
- discord.py - discord.py 主命令作为命令+参数的别名
- javascript - 词法范围代码之间的区别
- terraform - AWS VPC 私有/公共子网/Terraform?
- python - 如何为命令行脚本组织一个带有诗歌的python项目
- powershell - PowerShell - 通过将参数传递给 Select-Object,从多个制表符/CSV 分隔文件中获取基于多列的唯一行
- .net - 如何将具有日期时间模式的字符串映射到打字稿日期对象
- bash - 使用 vim 和 screen
- ios - 如何快速将数据从视图控制器传递到容器视图
- django - 确保数据位于 django 模板中正确的 tabe 列中
- php - 在所有运输方式名称前添加 WooCommerce 品牌名称