返回列表中向量的特定元素

huangapple go评论67阅读模式
英文:

Return specific element of vector in list

问题

> list = list(c("monday","tuesday","wednesday"),c("thursday","friday","saturday"),"sunday")
> list
[[1]]
[1] "monday"    "tuesday"   "wednesday"

[[2]]
[1] "thursday" "friday"   "saturday"

[[3]]
[1] "sunday"

> vector = c(2,3,1)
> vector
[1] 2 3 1

> goal=c("tuesday","saturday","sunday")
> goal
[1] "tuesday"  "saturday" "sunday" 

我可以这样获取每个列表元素的第一个元素:

lapply(list, function(x) x[1])

但是我无法使用矢量进行索引。

我还尝试将矢量转换为列表并附加它:

mapply(append, list, as.list(vector), SIMPLIFY = FALSE)

然后我会得到一个列表,其中每个元素的最后一个字符串是索引的字符串。但是我无法返回索引并将其用作数字以查找相应的字符串。

英文:

I have a list of vectors of strings. And I have a vector with indexes. I would like to return the indexed string in each list element.

> list = list(c("monday","tuesday","wednesday"),c("thursday","friday","saturday"),"sunday")
> list
[[1]]
[1] "monday"    "tuesday"   "wednesday"

[[2]]
[1] "thursday" "friday"   "saturday"

[[3]]
[1] "sunday"

> vector = c(2,3,1)
> vector
[1] 2 3 1

> goal=c("tuesday","saturday","sunday")
> goal
[1] "tuesday"  "saturday" "sunday" 

I can get the first element like this:

lapply(list,"[[",1)

but I cannot index the vector.

I also tried making the vector a list and append it:

mapply(append,list,as.list(vector),simplify=F)

And I get a list where the last string in each element is a string of the index. But I cannot return the index and use it as a numeric to find the respective string.

答案1

得分: 2

我不确定你为什么要在这里尝试使用append。你的第一个方法基本上是正确的:使用[[。但是你需要对索引和列表都进行映射,使用mapply

mapply(`[[`, list, vector)
英文:

I am unsure why you are trying to use append at all here. Your first approach was essentially correct: Use [[. But you need to map over the indices as well as the list, using mapply:

mapply(`[[`, list, vector)

答案2

得分: 1

有一个选项是使用来自tidyverse包集合的purrr。使用map_*而不是mapply的主要优势是在不同map变种之间保持一致的接口。

map2_chr(list, vector, `[[`)
英文:

There is also the option of using purrr from the tidyverse collection of packages. The main advantage of using map_* instead of mapply is the consistent interface between map variants.

map2_chr(list, vector, `[[`)

答案3

得分: 0

另一个选项:

unlist(Map(function(x, i) x[i], list, vector))
[1] "星期二"  "星期六" "星期日"
英文:

Another option:

unlist(Map(function(x, i) x[i], list, vector))
[1] "tuesday"  "saturday" "sunday" 

huangapple
  • 本文由 发表于 2023年6月19日 23:31:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76508096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定