我正在寻找解决以下问题的方法:我的第一个数据帧包含评级,例如,两个受试者(受试者 ID 1 和 2)在离散量表上对两个项目进行评分。
ratings <- data.frame(ID=c(1, 1, 2, 2), item=c(1, 2, 1, 2), rating=c(1, -4, 3, 2))
这将生成以下数据框:
ID item rating
1 1 1
1 2 -4
2 1 3
2 2 2
然后我有一个选择数据框,例如,两个受试者在 2 个项目之间进行选择。
choice <- data.frame(ID=c(1, 1, 2, 2), item_L=c(1, 2, 1, 2),
item_R=c(2,1,2,1), choice_item_Left=c(0,1,1,0))
这将生成以下数据框:
ID item_L item_R choice_item_Left
1 1 2 0
1 2 1 1
2 1 2 1
2 2 1 0
我现在的问题如下:我想访问评级数据帧,并将左侧和右侧项目的评级用作选择数据框中的新列,具体取决于 subjectID 和项目编号。因此,我需要选择数据框中的两个新列,即 rating_item_L 列和 rating_item_R,其值取决于评级数据框和评级数据框中的 ID。
示例数据帧如下所示:
ID item_1 item_2 choice_item_Left rating_item_L rating_item_R
1 1 1 2 0 1 -4
2 1 2 1 1 -4 1
3 2 1 2 1 3 2
4 2 2 1 0 2 3
至关重要的是,我有更多的选择而不是评级,并且评级是有序的(例如,从 1 到 20),但选择不是有序的。所以有项目3对9或2对8这样的选择。
有人知道解决方案吗?
你可以像这样使用merge
。
## merge left items
xx= merge(ratings,choice,by.x=c('ID','item'),by.y=c('ID','item_L'))
## merge right data
yy = merge(ratings,choice,by.x=c('ID','item'),by.y=c('ID','item_R'))
## bind left and right data
res <- merge(xx,yy,by=c('ID','item'))
# ID item rating.x item_R choice_item_Left.x rating.y item_L choice_item_Left.y
# 1 1 1 1 2 0 1 2 1
# 2 1 2 -4 1 1 -4 1 0
# 3 2 1 3 2 1 3 2 0
# 4 2 2 2 1 0 2 1 1
当然,您可以重新排列列并重命名它们以获得确切的输出。
setNames(res[,c("ID","item_R","item_L","choice_item_Left.x","rating.x","rating.y")],
c("ID","item_1","item_2","choice_item_Left","rating_item_L","rating_item_R"))
# ID item_1 item_2 choice_item_Left rating_item_L rating_item_R
# 1 1 2 2 0 1 1
# 2 1 1 1 1 -4 -4
# 3 2 2 2 1 3 3
# 4 2 1 1 0 2 2