资料
- Reshaping data with the reshape package
- http://had.co.nz/reshape/
- cran-reshape2.pdf
reshape2 可以将数据转换成你需要的各种格式,各种强大
- melt 指定读入数据的方式,dcast/acast 将数据重组成所需要的格式
- dcast输出data.frame,acast输出vector/matrix/array
参考:aggregation-and-restructuring-data-from-r-in-action/
melt
- id 指定做为键值的列
- measure.var 归并到 variable 的 列,如果不指定就是除了id之外的所有列
- value 在variable指定的列对应的取值
例子:
#data : subject time age weight height
# m_data:subject time variable value,其中variable为age/weight/height
m_data <- melt(data, id=c('subject', 'time'),measure.var = c('age', 'weight', 'height'))dcast/acast
- data 为已经melt的数据
- formula 指定结果数据的格式
- fun.aggregate 指定聚合的函数
- margins 指定显示统计的行/列
- subset 指定只取某个子集进行统计,例如subset = .(variable==”length”)
- fill 缺失元素的默认值
- value.var 用做值的列
注意:
- … 表示所有没在formula中出现的variables,也就是传到fun.aggregate里面的那些
- . 表示不区分剩余的行or列,直接统计,例如 formula = var ~ .
例子
# r_data : time subject weight age height 将数据变回原来的形状r_data <- cast(m_data, time + subject ~ variable)
# time, variable, SUBJA, SUBJB 其中SUBJA/SUBJB为subject的取值
dcast(melt_data,, ... ~ subject)
# 统计数据总数
cast(ffm, . ~ . , length)
#按treament分组统计数据
cast(ffm, treatment ~ . , length)
#以rep为一列,按treament取值为行,统计数据
cast(ffm, rep ~ treament, length)
#以 rep、treament为列,统计数据
cast(ffm, rep + treament ~ . , length)
#以 "rep_treament" 的取值为行,统计数据
cast(ffm , . ~ rep + treament, length)
#高维数据
cast(ffm, time ~ variable ~ treament, mean)
#按variable取值区分,然后按treament为列rep取值为行做分组统计,返回结果的列表的key值为variable的值
cast(ffm, treament ~ rep | variable, mean)
#加统计行/列
cast(ffm , treament ~ time , sum, margins = TRUE)
#加统计行/列
cast(ffm, treament + rep ~ time , sum, margins="treatment")
#统计函数返回多个值,treament Min. X1st.Qu. Median Mean X3rd.Qu. Max.
cast(ffm, treament ~ . , summary)
#treament 1_X1 1_X2 2_X1 2_X2,其中[X1,X2]标识range的上下界
cast(ffm, treament ~ rep, range)
#效果与range相同, treament 1_min 1_max 2_min 2_max
cast(ffm, treament ~ rep, c(min,max))
#treament min_1 min_2 max_1 max_2
cast(ffm, treament ~ result_variable + rep, c(min, max))
没有评论:
发表评论