如何使用一列来确定从何处获取另一列的值?

How can I use one column to determine where I get the value for another column?

我正在尝试使用一列来确定将哪一列用作另一列的值它看起来像这样:

     X   Y  Z   Target
1    a   b  c    X
2    d   e  f    Y
3    g   h  i    Z

我想要这样的东西:

     X   Y  Z   Target  TargetValue
1    a   b  c    X           a
2    d   e  f    Y           e
3    g   h  i    Z           i

其中每个TargetValue 是由Target 指定的列确定的值。我一直在使用 dplyr 来让它工作。如果我知道如何为 mutate 制作粘贴输入的输出,那就太好了,

mutate(TargetWordFixed = (paste("WordMove",TargetWord,".rt", sep="")))

但也许还有另一种方法可以做同样的事情。

温柔一点,我是 Whosebug 和 R 的新手...

您可以像这样尝试 apply 行:

transform(df, TargetValue = apply(df, 1, function(x) x[x["Target"]]))
#   X Y Z Target TargetValue
# 1 a b c      X           a
# 2 d e f      Y           e
# 3 g h i      Z           i

矢量化方法是使用矩阵子集:

df %>% mutate(TargetValue = .[cbind(1:n(), match(Target, names(.)))])
#  X Y Z Target TargetValue
#1 a b c      X           a
#2 d e f      Y           e
#3 g h i      Z           i

或者只使用 base R(同样的方法):

transform(df, TargetValue = df[cbind(1:nrow(df), match(Target, names(df)))])

解释:

  • match(Target, names(.)) 计算 Target 中条目的列索引(该列称为 X 等)
  • dplyr版本中的.是指你"pipe"用%>%进入mutate语句的数据(即它指的是df
  • df[cbind(1:n(), match(Target, names(df))] 创建一个矩阵,将 df 子集化为正确的值 - 矩阵的第一列只是从 1 开始到 df 的行数的行号(因此 1:nrow(df))矩阵中的第二列是索引,该列包含感兴趣的目标值(由 match(Target, names(df)) 计算)。

为示例数据子集生成的矩阵是:

cbind(1:nrow(df), match(df$Target, names(df)))
     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3
library(tidyverse)

df <-setNames(data.frame(cbind(matrix(letters[1:9],3,3,byrow=T), c("X", "Y", "Z"))), c("X", "Y", "Z", "Target"))

df

df %>% 
  gather(key="ID", value="TargetValue", X:Z) %>%
  filter(ID==Target) %>%
  select(Target, TargetValue) %>%
  left_join(df, by="Target")