我有一个小标题,其中一个变量是字符向量。我想提取该向量的一部分并连接以创建一个新字段。还有另外两个字段来确定开始索引和结束索引。这是一个玩具示例。
library(tidyverse)
df <-
tibble(id = seq(4),
y = list(letters[1:4], letters[2:7], letters[3:10], letters[3:7]),
start_pos = c(2, 1, 3, 2),
end_pos = c(2, 3, 5, 3))
df
#> # A tibble: 4 x 4
#> id y start_pos end_pos
#> <int> <list> <dbl> <dbl>
#> 1 1 <chr [4]> 2 2
#> 2 2 <chr [6]> 1 3
#> 3 3 <chr [8]> 3 5
#> 4 4 <chr [5]> 2 3
我提出了以下解决方案,但这(尤其是lapply
部分)似乎不必要地复杂。有没有更聪明的方法来获得相同的结果?
df %>%
mutate(strng =
lapply(seq(length(y)), function(x) y[[x]][start_pos[x]:end_pos[x]] %>% paste(collapse = " "))) %>%
unnest(strng)
#> # A tibble: 4 x 5
#> id y start_pos end_pos strng
#> <int> <list> <dbl> <dbl> <chr>
#> 1 1 <chr [4]> 2 2 b
#> 2 2 <chr [6]> 1 3 b c d
#> 3 3 <chr [8]> 3 5 e f g
#> 4 4 <chr [5]> 2 3 d e
由reprex package于2020年6月6日创建(v0.3.0)
最佳答案
您可以使用rowwise()
:
library(dplyr)
df %>%
rowwise() %>%
mutate(strng = paste(y[start_pos:end_pos], collapse = " ")) %>%
ungroup()
# # A tibble: 4 x 5
# id y start_pos end_pos strng
# <int> <list> <dbl> <dbl> <chr>
# 1 1 <chr [4]> 2 2 b
# 2 2 <chr [6]> 1 3 b c d
# 3 3 <chr [8]> 3 5 e f g
# 4 4 <chr [5]> 2 3 d e
关于r - 提取向量的一部分并以整齐的方式连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62229183/