use*_*065 3 format r reshape reshape2 tidyr
我有一个长格式数据帧狗,我正在尝试使用reshape()函数重新格式化为宽.它目前看起来像这样:
dogid month year trainingtype home school timeincomp
12345 1 2014 1 1 1 340
12345 2 2014 1 1 1 360
31323 12 2015 2 7 3 440
31323 1 2014 1 7 3 500
31323 2 2014 1 7 3 520
Run Code Online (Sandbox Code Playgroud)
dogid列是一堆id,每只狗一个.12个月和2014年至2015年的月份列为1到12之间.培训类型在1到2之间变化.每只狗每个月 - 年 - 训练类型组合都有一个timeincomp值,因此每只狗有48个条目.家庭和学校从1-8不等,每只狗都是不变的(同一只狗的每个入口都有相同的学校和家庭).comp中的时间是我的响应变量.
我希望我的桌子看起来像这样:
dogid home school month1year2014trainingtype1 month2year2014trainingtype1
12345 1 1 340 360
31323 7 3 500 520
Run Code Online (Sandbox Code Playgroud)
等(每个月 - 年 - 训练类型组合的列)
我应该在重塑中使用哪些参数来实现这一目标?
您可以使用dcast包中的功能reshape2.这更容易理解.公式的左侧是长的,而右侧是宽的.
fun.aggregate是在每个案例中有超过1个数字的情况下应用的函数.如果您确定没有重复的案例,可以使用mean或sum
dcast(data, formula= dogid + home + school ~ month + year + trainingtype,
value.var = 'timeincomp',
fun.aggregate = sum)
Run Code Online (Sandbox Code Playgroud)
我希望它有效:
dogid home school 1_2014_1 2_2014_1 12_2015_2
1 12345 1 1 340 360 0
2 31323 7 3 500 520 440
Run Code Online (Sandbox Code Playgroud)
在这种情况下,使用base reshape,您实际上需要interaction()三个时间变量中的一个来定义您的宽变量,因此:
idvars <- c("dogid","home","school")
grpvars <- c("year","month","trainingtype")
outvar <- "timeincomp"
time <- interaction(dat[grpvars])
reshape(
cbind(dat[c(idvars,outvar)],time),
idvar=idvars,
timevar="time",
direction="wide"
)
# dogid home school timeincomp.2014.1.1 timeincomp.2014.2.1 timeincomp.2015.12.2
#1 12345 1 1 340 360 NA
#3 31323 7 3 500 520 440
Run Code Online (Sandbox Code Playgroud)