将一列中的值应用到新列

问题描述

我有一个包含多列的数据框,每列对应于不同刺激的评级。我还有列指示每个参与者看到每个项目的顺序。每行是一个参与者。

x <- data.frame("post1" = c(1,NA,2,3,NA),#stimuli ratings columns
                "post2" = c(3,1,4),"post3" = c(NA,4,"firstpost" = c("post3","post1","post3","post6","post4"),#stimuli order columns
                "secondpost" = c("post2","post4","post1"))

我想按照他们看到刺激的顺序制作另一组列,其中包含来自第一组列(“post1”等)的值(评级) - 例如,如果他们首先看到帖子 3,新列的评分将是第 3 篇。类似如下:

firstpostrating <- c(4,2)
secondpostrating <- c(1,1)

我需要一种方法来为他们看到的每个刺激从相应的刺激列中获取值。我希望得到的结果是第一、第二、第三刺激和相应评级的列 - 这样我就可以查看顺序效应。

非常感谢您为此编写函数的任何帮助!

解决方法

这里我提供一种解决方案。 我使用的示例数据 x 与您的略有不同。因为为了一致性,示例数据不应包含 post6post4

library(data.table)
x <- data.table(post1 = c(1,NA,2,3,4),#stimuli ratings columns
                post2 = c(3,1,5),post3 = c(2,4,firstpost = c("post3","post1","post3","post2","post1"),#stimuli order columns
                secondpost = c("post2","post1"))
x
#>    post1 post2 post3 firstpost secondpost
#> 1:     1     3     2     post3      post2
#> 2:    NA     1     3     post1      post3
#> 3:     2    NA     1     post3      post2
#> 4:     3     2     4     post2      post3
#> 5:     4     5     5     post1      post1
x[,`:=`(firstpostrate  = get(firstpost),secondpostrate = get(secondpost)),by = post1]
x
#>    post1 post2 post3 firstpost secondpost firstpostrate secondpostrate
#> 1:     1     3     2     post3      post2             2              3
#> 2:    NA     1     3     post1      post3            NA              3
#> 3:     2    NA     1     post3      post2             1             NA
#> 4:     3     2     4     post2      post3             2              4
#> 5:     4     5     5     post1      post1             4              4

reprex package (v2.0.0) 于 2021 年 4 月 29 日创建