有几次dplyr会删除rownames,现在版本0.3已经这样做了。
我经常使用行名来在数据框中保存的不同标识符之间进行转换,如下所示:
test <- data.frame(Greek = c("Alpha", "Beta", "Gamma"), Letters = LETTERS[1:3])
rownames(test) <-test$Letters
lookup <- c("C", "B")
test[lookup, "Greek"]
[1] Gamma Beta
Levels: Alpha Beta Gamma
由于缺少rownames,现在dplyr
失败了library(dplyr)
test <- tbl_df(data.frame(Greek = c("Alpha", "Beta", "Gamma"), Letters = LETTERS[1:3]))
rownames(test) <-test$Letters
lookup <- c("C", "B")
test[lookup, "Greek"]
Source: local data frame [2 x 1]
Greek
1 NA
2 NA
我尝试过使用filter()和select(),但找不到保留查找顺序的解决方案。
答案 0 :(得分:2)
这是您可以使用match
es:
test[match(lookup,test$Letters),"Greek"]
[1] Gamma Beta
Levels: Alpha Beta Gamma
你可以用do
换行使其成为dplyr-ic:
test %>% do(`[`(.,match(lookup,.$Letters),)) %>% select(Greek)
Source: local data frame [2 x 1]
Greek
1 Gamma
2 Beta
或者正如@hadley所提到的那样,left_join
能够满足您的需求:
left_join(data.frame(Letters=lookup),test) %>% select(Greek)
Joining by: "Letters"
Greek
1 Gamma
2 Beta