如何解决dcast中是否有一个允许我包含其他条件的功能?
我正在尝试创建一个仅包含一些长格式数据的宽格式数据集。这是学习者通过在线学习模块获得的数据,有时他们会“卡住”在屏幕中,因此在该屏幕上记录了多次尝试。
lesson_long <- data.frame (id = c(4256279,4256279,4256308,4256308),screen = c("survey1","survey1","survey2","survey2"),question_attempt = c(1,1,2,1),variable = c("age","country","age","education","course","course"),response = c(0,5,20,3,18,4,1 ))
。
id screen question_attempt variable response
4256279 survey1 1 age 0
4256279 survey1 1 country 5
4256279 survey1 2 age 20
4256279 survey1 2 country 5
4256279 survey2 1 education 3
4256279 survey2 1 course 2
4256308 survey1 1 age 18
4256308 survey1 1 country 5
4256308 survey2 1 education 4
4256308 survey2 1 course 1
对于我的分析,我只需要在每个屏幕上的最后一次尝试中包括他们的回答(或在他们最大的question_attempt上的响应-有时每个屏幕最多可以进行8或9次尝试)。先前的所有尝试都将被取消,我不需要最终数据集中的屏幕名称。最终的宽格式如下所示:
id age country education course
4256279 20 5 3 2
4256308 18 5 4 1
我一直试图通过dcast来做到这一点(失败):
lesson_wide <- dcast(lesson_long,`id` ~ variable,value.var = "response",fun.aggregate = max("question_attempt"),fill=0)
fun.aggregate显然无法正常工作,但是我有解决方案吗?还是在使用dcast之前我需要一个额外的步骤来选择数据?但是如果那是解决方案,该怎么办?
很好奇看到您的答案。预先感谢!
解决方法
您可以通过order
,id
和screen
question_attempt
来选择数据,并选择每个last
的{{1}}值。
question_attempt
类似地,使用library(data.table)
setDT(lesson_long)
dcast(lesson_long[order(id,screen,question_attempt)],id~variable,value.var = 'response',fun.aggregate = last,fill = NA)
# id age country course education
#1: 4256279 20 5 2 3
#2: 4256308 18 5 1 4
和dplyr
:
tidyr
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。