R变换列表中的字符矢量,条件是矢量的内容



问题是我有一个字符向量列表。

示例:

mylist <- list( c("once","upon","a","time"),
c("once", "in", "olden", "times"),
c("Let","all","good","men"),
c("Let","This"),
c("once", "is","never","enough"),
c("in","the"),
c("Come","dance","all","around"))

并且我想要将c("一"、"二"(前置到从"一"开始的那些向量;一次";以列表结束

mylist <- list( c("one", "two", "once","upon","a","time"),
c("one", "two", "once", "in", "olden", "times"),
c("Let","all","good","men"),
c("Let","This"),
c("one", "two", "once", "is","never","enough"),
c("in","the"),
c("Come","dance","all","around"))

到目前为止

我可以选择相关的矢量

mylist[grep("once",mylist)]

并且我可以准备";一个";以及";两个";创建结果列表

resultlist <- lapply(mylist[grep("once",mylist)],FUN = function(listrow) prepend(listrow,c("One","Two")))

但是把结果放在mylist的正确位置?

不,我没想到!

提示,提示和解决方案最受欢迎:-(

  • 我们可以使用
lapply(mylist , (x) if(grepl("once" , x[1])) 
append(x,  c("one", "two") , 0) else x)
  • 输出
[[1]]
[1] "one"  "two"  "once" "upon" "a"    "time"
[[2]]
[1] "one"   "two"   "once"  "in"    "olden" "times"
[[3]]
[1] "Let"  "all"  "good" "men" 
[[4]]
[1] "Let"  "This"
[[5]]
[1] "one"    "two"    "once"   "is"     "never"  "enough"
[[6]]
[1] "in"  "the"
[[7]]
[1] "Come"   "dance"  "all"    "around"

我认为您根本不需要grep。循环列表,检查"once"的第一个值,并通过c()附加额外值:

lapply(mylist, (x) if(x[1] == "once") c("one", "two", x) else x)
##[[1]]
##[1] "one"  "two"  "once" "upon" "a"    "time"
##
##[[2]]
##[1] "one"   "two"   "once"  "in"    "olden" "times"
##
##[[3]]
##[1] "Let"  "all"  "good" "men" 
##
##[[4]]
##[1] "Let"  "This"
##
##[[5]]
##[1] "one"    "two"    "once"   "is"     "never"  "enough"
##
##[[6]]
##[1] "in"  "the"
##
##[[7]]
##[1] "Come"   "dance"  "all"    "around"

map_if的另一个选项

library(purrr)
map_if(mylist, .p = ~ first(.x) == "once", .f = ~ c("one", "two", .x))

-输出

[[1]]
[1] "one"  "two"  "once" "upon" "a"    "time"
[[2]]
[1] "one"   "two"   "once"  "in"    "olden" "times"
[[3]]
[1] "Let"  "all"  "good" "men" 
[[4]]
[1] "Let"  "This"
[[5]]
[1] "one"    "two"    "once"   "is"     "never"  "enough"
[[6]]
[1] "in"  "the"
[[7]]
[1] "Come"   "dance"  "all"    "around"

最新更新