我實現了兩個函數reshape_long
和reshape_wide
(請參閱下面的完整工作示例)以重新塑造數據幀。 我創建了幾個小例子,這兩個函數似乎正常工作。使用dcast重構數據幀並融化
但是,在我的真實數據集(大約200.000到300.000行)上使用reshape_wide
函數 失敗。會發生什麼情況是將X,Y和Z的所有值都設置爲1. 我的實際數據結構與下面的小示例完全相同。工作2天后,我認爲 的問題是,「主鍵」(test_name
,group_name
和id
)只是在廣泛的形式是唯一的。在應用 reshape_long
函數後,主鍵不再是唯一的。我想知道,有誰能告訴我d1 -> reshape_wide -> d2
的步驟 是否可以工作,因爲d1
的非唯一性?
library(reshape2)
library(taRifx)
reshape_long <- function(data, ids) {
# Bring data into long form
data_long <- melt(data, id.vars = ids,
variable.name="Data_Points", value.name="value")
data_long$value <- as.numeric(data_long$value)
# Remove rows were analyte value is NA
data_long <- data_long[!is.na(data_long$value), ]
# Resort data
formula_sort <- as.formula(paste("~", paste(ids, collapse="+")))
data_long <- sort(data_long, f = formula_sort)
return(data_long)
}
reshape_wide <- function(data, ids) {
# Bring data into wide form
formula_wide <- as.formula(paste(paste(ids, collapse="+"),
"~ Data_Points"))
data_wide <- dcast(data, formula_wide)
# Resort data
formula_sort <- as.formula(paste("~", paste(ids, collapse="+")))
data_wide <- sort(data_wide, f = formula_sort)
return(data_wide)
}
d <- data.frame(
test_name = c(rep("Test_A", 6), rep("Test_B", 6)),
group_name = c(rep("Group_C", 3), rep("Group_D", 3),
rep("Group_C", 3), rep("Group_D", 3)),
id = c("I1", "I2", "I3", "I4", "I5", "I6",
"I1", "I2", "I3", "I7", "I8", "I9"),
X = c(NA,NA,1,2,3,4,5,6,NA,7,8,9),
Y = as.numeric(10:21),
Z = c(NA,22,23,NA,24,NA,25,26,NA,27,28,29)
)
d
d1 <- reshape_long(d, ids=c("test_name", "group_name", "id"))
d1
d2 <- reshape_wide(d1, ids=c("test_name", "group_name", "id"))
d2
identical(d,d2)