我想将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的常见元素是“unit”(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参数/函数中的list
和data.frame
。有人可以帮忙吗?
答案 0 :(得分:2)
我们可以使用Map
来提取“描述”&#39;列基于&#39; list.1&#39;
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"
答案 1 :(得分:1)
我们可以对列表中的每个元素使用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"