假设我有一个如下所示的数据框:
dframe = data.frame(x = c(1, 2, 3), y = c(4, 5, 6))
并且假设我想自适应地抓取一个不同的列,这样,对于dframe的每一行,我得到colname = c('x', 'y', 'x')
我想做一些类似于dframe[, colname]
的东西来获得c(1,5,3)。
这可能在R?怎么样?
我最喜欢的旧矩阵索引将负责这一点。只需传递一个带有相应行/列索引的2列矩阵:
rownames(dframe) <- seq_len(nrow(dframe))
dframe[cbind(rownames(dframe),colname)]
#[1] 1 5 3
或者,如果您不想添加rownames:
dframe[cbind(seq_len(nrow(dframe)), match(colname,names(dframe)))]
#[1] 1 5 3
可以使用mapply
传递rownumber
(dframe
)的参数和列名称(每行)的向量来返回特定的列值。
使用mapply
的解决方案可以是:
dframe = data.frame(x = c(1, 2, 3), y = c(4, 5, 6))
colname = c('x', 'y', 'x')
mapply(function(x,y)dframe[x,y],1:nrow(dframe), colname)
#[1] 1 5 3
虽然,下一个选项可能不是很直观,但如果有人想在dplyr
链中找到解决方案,那么使用gather
的方法可以是:
library(tidyverse)
data.frame(colname = c('x', 'y', 'x'), stringsAsFactors = FALSE) %>%
rownames_to_column() %>%
left_join(dframe %>% rownames_to_column() %>%
gather(colname, value, -rowname),
by = c("rowname", "colname" )) %>%
select(rowname, value)
# rowname value
# 1 1 1
# 2 2 5
# 3 3 3