首页 > 解决方案 > 如何以与我的订单矩阵中相同的顺序每行更改列

问题描述

我有一个矩阵,其中存储了问卷项目的顺序,其中第一列包含第一次显示的项目的名称,第二列包含第二个显示的项目,依此类推。该矩阵中的每一行代表一个新问卷, 具有相同的项目,但顺序以不同的顺序随机化。

> order.matrix
     [,1]    [,2]    [,3]   
[1,] "Anger" "Happy" "Sad"  
[2,] "Happy" "Sad"   "Anger"
[3,] "Sad"   "Anger" "Happy"

我已将项目的响应存储在数据框中:

> df.responses
  Anger Happy Sad
1     1     2   3
2     3     2   0
3     9     2   1

现在,我想更改 中的响应顺序,以便df.responses它们类似于行中的项目顺序。(因此, 的列名不应再出现在结果 df 中。)此示例中的结果应如下所示:order.matrixdf.responses

> df.result
  V1 V2 V3
1  1  2  3
2  2  0  3
3  1  9  2

我怎么能/应该这样做?

编辑,由于评论:我想用order.matrix相应的值替换项目名称df.responses

标签: r

解决方案


1.创建可重现的示例

order.matrix <- matrix(c("Anger", "Happy", "Sad", "Happy", "Sad","Anger", "Sad", "Anger", "Happy"),
                       ncol=3,
                       byrow=TRUE)

df.responses <-matrix(c(1, 2, 3, 3, 2, 0, 9, 2, 1),
                        ncol=3,
                        byrow=TRUE)
colnames(df.responses) <- c("Anger", "Happy", "Sad")

2.使用base的解决方案R

result <- NULL
for (i in seq_along(order.matrix[, 1])) {
  result <- rbind(result, df.responses[i, order.matrix[i, ]])
}
colnames(result) <- c("V1", "V2", "V3")

        V1    V2  V3
[1,]     1     2   3
[2,]     2     0   3
[3,]     1     9   2

推荐阅读