首页 > 解决方案 > 有条件地将字符串连接到多行

问题描述

我从包含多行字符串的 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

希望这是有道理的,感谢任何帮助!

标签: rstringstring-concatenation

解决方案


tidyverse方法是到具有先前非 NA 值fill的列然后和在一起。actiongroup_by Actionpastedescription

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        

推荐阅读