2017-07-19 37 views
2

我想匹配list的元素與data.frame的元素。結果應該是list使用lapply匹配列表元素和數據幀值(查找表)

所以,這裏是一個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 

列表和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。誰能幫忙?

回答

1

我們可以使用Mapunit在數據幀基礎上從「list.1」

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

另外一個有趣的選擇,謝謝! – Ezra

1

我們可以使用lapply在列表中每個元素的索引來提取「描述」一欄,然後match他們,獲得相應的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" 
+0

作品完美&精益,謝謝。 – Ezra

相關問題