r - 如何以与我的订单矩阵中相同的顺序每行更改列
问题描述
我有一个矩阵,其中存储了问卷项目的顺序,其中第一列包含第一次显示的项目的名称,第二列包含第二个显示的项目,依此类推。该矩阵中的每一行代表一个新问卷, 具有相同的项目,但顺序以不同的顺序随机化。
> 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.matrix
df.responses
> df.result
V1 V2 V3
1 1 2 3
2 2 0 3
3 1 9 2
我怎么能/应该这样做?
编辑,由于评论:我想用order.matrix
相应的值替换项目名称df.responses
解决方案
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
推荐阅读
- computer-science - 为常规语言抽取引理:我们可以将第一个条件修改为“对于每个 i > 0”吗?
- python - 在 Azure 上注册模型时出现“证书验证失败”错误
- java - com.mysql 的数据源实现的名称是什么?
- list - 使用已排序的内部数据类创建 Kotlin 数据类的新实例
- uml - Include和Exclude的区别和目的是什么?
- mapping - 尝试在 CartoDB 中按列值设置颜色点
- python - 为什么我的代码无法将列表的每个项目从字符串转换为整数?
- php - 如何在 API 注册中实现 Laravel 的 Must Verify Email 功能?
- bash - 我需要用 sed 命令删除两个“”
- android - android中的1000个问题需要创建1000个活动?