我寫了兩個包裝函數用於投射和融化,以將我的數據從長條形碼 變爲寬幅形式,反之亦然。然而,我仍然在努力使功能 reshape_wide
它把長形式的數據變成寬的形式。R重塑數據從長到寬,反之亦然
以下是我的示例函數和運行它的代碼。我創建了一個寬的 格式的dummy data.frame,我使用我的reshape_long
函數將其重塑爲長格式,然後使用我的reshape_wide
函數將其轉換回原始寬格式。但是,重塑失敗的原因是我無法想象它。看來dcast
中使用的公式是錯誤的。
reshape_long <- function(data, identifiers) {
data_long <- melt(data, id.vars = identifiers,
variable.name="name", value.name="value")
data_long$value <- as.numeric(data_long$value)
data_long <- data_long[!is.na(data_long$value), ]
return(data_long)
}
reshape_wide <- function(data, identifiers, name) {
if(is.null(identifiers)) {
formula_wide <- as.formula(paste(paste(identifiers,collapse="+"),
"series ~ ", name))
} else {
formula_wide <- as.formula(paste(paste(identifiers,collapse="+"),
"+ series ~ ", name))
}
series <- ave(1:nrow(data), data$name, FUN=function(x) { seq.int(along=x) })
data <- cbind(data, series)
data_wide <- dcast(data, formula_wide, value.var="value")
data_wide <- data_wide[,!(names(data_wide) %in% "series")]
return(data_wide)
}
data <- data.frame(ID = rep("K", 6), Type = c(rep("A", 3), rep("B", 3)),
X = c(NA,NA,1,2,3,4), Y = 5:10, Z = c(NA,11,12,NA,14,NA))
data <- reshape_long(data, identifiers = c("ID", "Type"))
data
reshape_wide(data, identifiers = c("ID", "Type"), name="name")
這裏是我的右輸出鏈接,當我運行上面的代碼:
什麼是錯的,在列B型出現5次,而不是3倍,因爲它應該是。 你有相同的data.frame嗎?
這裏是sessionInfo()
> sessionInfo()
R version 2.14.0 (2011-10-31)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)
locale:
[1] C
attached base packages:
[1] grid stats graphics grDevices utils datasets methods
[8] base
other attached packages:
[1] reshape2_1.2.1 outliers_0.14 lme4_0.999375-42
[4] Matrix_1.0-1 gregmisc_2.1.2 gplots_2.10.1
[7] KernSmooth_2.23-7 caTools_1.12 bitops_1.0-4.1
[10] gtools_2.6.2 gmodels_2.15.1 gdata_2.8.2
[13] lattice_0.20-0 dataframes2xls_0.4.5 RankProd_2.26.0
[16] R.utils_1.9.3 R.oo_1.8.3 R.methodsS3_1.2.1
[19] xlsx_0.3.0 xlsxjars_0.3.0 rJava_0.9-2
[22] rj_1.0.0-3
loaded via a namespace (and not attached):
[1] MASS_7.3-16 nlme_3.1-102 plyr_1.6 rj.gd_1.0.0-1 stats4_2.14.0
[6] stringr_0.5 tools_2.14.0
這適用於我的機器。你使用的是什麼版本的重塑包?也許將'sessionInfo()'的結果添加到你的問題中。 – Andrie 2012-03-07 15:44:06