gpt4 book ai didi

r - 超前或滞后函数可获取多个值,而不仅仅是第n个

转载 作者:行者123 更新时间:2023-12-04 03:03:07 25 4
gpt4 key购买 nike

我有一个小标题,每行有一个单词列表。我想从一个搜索关键字的函数中创建一个新变量,如果找到该关键字,则创建一个由关键字正负3个单词组成的字符串。

下面的代码很接近,但是与其捕获我的关键字前后的所有三个单词,不如捕获,而是捕获了单词3的前后。

df <- tibble(words = c("it", "was", "the", "best", "of", "times", 
"it", "was", "the", "worst", "of", "times"))
df <- df %>% mutate(chunks = ifelse(words=="times",
paste(lag(words, 3),
words,
lead(words, 3), sep = " "),
NA))

最直观的解决方案是lag函数是否可以执行以下操作:lead(words, 1:3),但不起作用。

显然,我可以很快地手动完成此操作(paste(lead(words,3), lead(words,2), lead(words,1),...lag(words,3)),但是我最终实际上希望能够获取50个上下左右的关键字,以至于无法手工编码。

如果tidyverse中存在解决方案,那将是理想的选择,但是任何解决方案都将有所帮助。任何帮助,将不胜感激。

最佳答案

一种选择是sapply:

library(dplyr)

df %>%
mutate(
chunks = ifelse(
words == "times",
sapply(
1:nrow(.),
function(x) paste(words[pmax(1, x - 3):pmin(x + 3, nrow(.))], collapse = " ")
),
NA
)
)

输出:
# A tibble: 12 x 2
words chunks
<chr> <chr>
1 it NA
2 was NA
3 the NA
4 best NA
5 of NA
6 times the best of times it was the
7 it NA
8 was NA
9 the NA
10 worst NA
11 of NA
12 times the worst of times

尽管它不是显式的 leadlag函数,但通常也可以达到目的。

关于r - 超前或滞后函数可获取多个值,而不仅仅是第n个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55010810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com