【问题标题】:Using lapply to match list elements and dataframe values (lookup-table)使用 lapply 匹配列表元素和数据框值(查找表)
【发布时间】:2017-12-24 07:18:31
【问题描述】:

我想将list 的元素与data.frame 的元素相匹配。结果应该又是list

所以,这里是data.frame

data.f <- data.frame(seq(1:3), c("1", "1,3", "2,3,4"))
names(data.f) <- c("unit", "description")
> data.f
  unit description
1    1           1
2    2         1,3
3    3       2,3,4

这是列表

list.1 <- list(c(1), c(2,3), c(2), c(1,3))
> list.1
[[1]]
[1] 1

[[2]]
[1] 2 3

[[3]]
[1] 2

[[4]]
[1] 1 3

list 和 data.frame 的共同元素是“单元”(1、2、3)。我需要一个新列表,其中包含“描述”而不是单位。同样,可以将一个以上的参数传递给每个列表元素。

结果应如下所示:

list.result <- list(c("1"), c("1,3", "2,3,4"), c("1,3"), c("1", "2,3,4"))
> list.result
[[1]]
[1] "1"

[[2]]
[1] "1,3"   "2,3,4"

[[3]]
[1] "1,3"

[[4]]
[1] "1"     "2,3,4"  

我认为lapply是这里选择的功能吗?虽然我不确定如何匹配 lapply 参数/函数中的 listdata.frame。有人可以帮忙吗?

【问题讨论】:

    标签: r list dataframe match lapply


    【解决方案1】:

    我们可以使用Map根据'list.1'中的索引提取'description'列

    Map(`[`,list(as.character(data.f$description)), list.1)
    #[[1]]
    #[1] "1"
    
    #[[2]]
    #[1] "1,3"   "2,3,4"
    
    #[[3]]
    #[1] "1,3"
    
    #[[4]]
    #[1] "1"     "2,3,4"
    

    【讨论】:

      【解决方案2】:

      我们可以将lapply 用于列表中的每个元素,然后将match 与数据框中的unit 一起使用,并获得相应的description 值。

      lapply(list.1, function(x) as.character(data.f$description[match(x, data.f$unit)]))
      
      #[[1]]
      #[1] "1"
      
      #[[2]]
      #[1] "1,3"   "2,3,4"
      
      #[[3]]
      #[1] "1,3"
      
      #[[4]]
      #[1] "1"     "2,3,4"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-19
        • 1970-01-01
        相关资源
        最近更新 更多