如何使用一列来确定我在哪里获得另一列的值?

时间:2015-02-21 01:21:46

标签: r dataframe dplyr

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

     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="")))

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

温柔,我是stackoverflow和R ...的新手。

3 个答案:

答案 0 :(得分:2)

您可以像这样逐行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

答案 1 :(得分:2)

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

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

或者只是使用基础R(相同的方法):

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

说明:

  • match(Target, names(.))计算Target中条目的列索引(该列名为X等)
  • dplyr版本中的.是指您管道的数据"使用%>%进入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

答案 2 :(得分:0)

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")