R从带有向量的数据帧中提取值

时间:2018-07-02 10:38:04

标签: r subset

我希望我的问题不会重复,但是我确实找不到我需要的东西。我潜入dplyr,甚至从DataCamp参加了data.table课程,但我无法解决。也许俯视什么?

我有这个df:

set.seed(1964)
df<-data.frame(id = c( "XEY", "NZH", "DYE", "JNF", "LHH", "WNB"),
           q_1 = sample(5,6, replace = TRUE),
           q_2 = sample(5,6, replace = TRUE),
           q_3 = sample(5,6, replace = TRUE),
           q_4 = sample(5,6, replace = TRUE),
           q_5 = sample(5,6, replace = TRUE))

所以我的df看起来像这样:

enter image description here

接下来,我有两个向量,分别是id(行指示符)和q(问题号),如下所示:

id <- c("XEY", "DYE", "JNF", "DYE", "XEY", "LHH", "WNB", "JNF" )
question <- c("val_1", "val_1","val_3","val_3","val_3", "val_4", "val_4", "val_5")

我想使用两个向量从df中提取值,以获得如下输出:

enter image description here

我尝试了很多事情来提取值,但是我一直在出错。我已经尝试过类似的事情:

df[id == (id[1]), (question[1])]
df[id == id[1], question[1]]

奇怪的是,data.table包似乎接受“行符号”。因为:

df[id == (id[1]),]

返回“ XEY”行的值:

    id q_1 q_2 q_3 q_4 q_5
1: XEY   5   1   5   4   1

但是如何使用我的向量为正确的列表示法做些技巧?

很抱歉这个非常基本的问题,感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

你可以用提迪尔做。 我在您的df中添加了stringsAsFactors = FALSE,以避免在加入过程中出现警告。

set.seed(1964)
df<-data.frame(id = c( "XEY", "NZH", "DYE", "JNF", "LHH", "WNB"),
       q_1 = sample(5,6, replace = TRUE),
       q_2 = sample(5,6, replace = TRUE),
       q_3 = sample(5,6, replace = TRUE),
       q_4 = sample(5,6, replace = TRUE),
       q_5 = sample(5,6, replace = TRUE),stringsAsFactors=FALSE)
id <- c("XEY", "DYE", "JNF", "DYE", "XEY", "LHH", "WNB", "JNF" )
question <- c("q_1", "q_1","q_3","q_3","q_3", "q_4", "q_4", "q_5")

library(tidyr)
df2 <- data.frame(id,question,stringsAsFactors=FALSE)
df %>% gather(k,Value,-id) %>% inner_join(df2,by="id") %>% filter(question==k) %>% arrange(question) %>%
    select(-k)

答案 1 :(得分:3)

在base R中,您可以执行以下操作。

Value <- diag(as.matrix(df[match(id, df$id), sub("val", "q", question)]))
result <- data.frame(id, Question = sub("val", "q", question), Value)
result
#   id Question Value
#1 XEY      q_1     5
#2 DYE      q_1     1
#3 JNF      q_3     2
#4 DYE      q_3     1
#5 XEY      q_3     5
#6 LHH      q_4     2
#7 WNB      q_4     2
#8 JNF      q_5     3

编辑。

在看到@ Nicolas2的答案并使用inner_join之后,我决定尝试merge。但是要做到这一点,我将需要外部软件包melt中的函数reshape2

df2 <- data.frame(id, question = sub("val", "q", question))
df3 <- reshape2::melt(df, id.vars = "id")
names(df3)[2] <- "question"
result2 <- merge(df2, df3)
result2
#   id question value
#1 DYE      q_1     1
#2 DYE      q_3     1
#3 JNF      q_3     2
#4 JNF      q_5     3
#5 LHH      q_4     2
#6 WNB      q_4     2
#7 XEY      q_1     5
#8 XEY      q_3     5

结果相同,但行顺序不同。