按位置从一个数据框到另一个数据框获取元素

时间:2017-03-21 12:26:00

标签: r

我们假设我们有两个数据框:

df1 <- data.frame(A = letters[1:3], B = letters[4:6], C = letters[7:9], stringsAsFactors = FALSE)
  A B C
1 a d g
2 b e h
3 c f i

df2 <- data.frame(V1 = 1:3, V2 = 4:6, V3 = 7:9)
  V1 V2 V3
1  1  4  7
2  2  5  8
3  3  6  9

我需要构建一个函数,它将一个值或一个包含来自其中一个数据帧的元素的向量作为输入,并根据它们的位置索引从另一个数据帧中返回元素。

该功能应该像这样工作:

> matchdf(values = c("a", "e", "i"), dfin = df1, dfout = df2)
[1] 1 5 9

> matchdf(values = c(1, 5, 9), dfin = df2, dfout = df1)
[1] "a" "e" "i"

> matchdf(values = c(1, 1, 1), dfin = df2, dfout = df1)
[1] "a" "a" "a"

这是我到目前为止所尝试的:

requiere(dplyr)
toVec   <- function(df) df %>% as.matrix %>% as.vector
matchdf <- function(values, dfin, dfout) toVec(dfout)[toVec(dfin) %in% values]

# But sometimes the output values aren't in correct order:
> matchdf(c("c", "i", "h"), dt1, dt2)
[1] 3 8 9
# should output 3 9 8

> matchdf(values = c("a", "a", "a"), dfin = dt1, dfout = dt2)
[1] 1
# Should output 1 1 1

如果它可以轻松完成任务,请随意使用data.table或/和dplyr。我更喜欢没有for循环的解决方案。

假设

    来自df1的
  • 元素与df2
  • 不同
  • dim(df1)= dim(df2)

1 个答案:

答案 0 :(得分:-1)

matchdf <- function(values, dfin, dfout){
        unlist(sapply(values, 
                      function(val) dfout[dfin == val], 
                      USE.NAMES = F)
               )
}

matchdf(c("c", "i", "h"), df1, df2)
#should output 3 9 8
[1] 3 9 8
matchdf(values = c("a", "a", "a"), dfin = df1, dfout = df2)
#should output 1 1 1
[1] 1 1 1
matchdf(values = c("X", "Y", "a"), dfin = df1, dfout = df2)
#should output vector, not list
[1] 1