[英]Transposing rows into columns, then split them
我有一個數據集,其中包含按以下行排序的數據:
*VarName1* - *VarValue1*
*VarName2* - *VarValue2*
*Etc.*
我希望VarNames成為單獨的列。 我通過使用以下代碼實現了這一點:
DFP1 <- as.data.frame(t(DFP)) #DFP contains the data
現在,這是一個非常大的數據集。 它包含多年(數百萬行)的數據。 上面的代碼創建一個具有> 1E6列的數據框。 我需要按每個條目拆分這些列。 我看到在第一段數據中,每第86列都會重復出現一個新條目。 所以,我嘗試了這個:
tmp <- data.frame(
X = DFP$noFloat,
ind = rep(1:86, nrow(DFP)/86)
)
y <- rbind(DFP$nmlVar[1:86], unstack(tmp, X~ind))
這適用於幾行。 問題是這些年來變量的數量增加了,我不能簡單地假設每個條目的變量數量是相同的。 這導致變量值與名稱不匹配。 我正在尋找一種基於變量和值的變量名來匹配它們的方法。
我是高級數據分析的新手,所以如果您還需要其他任何信息,請告訴我。
編輯:我創建了一些DFP外觀的示例數據,希望可以使您更好地理解我的問題:
DFP <- data.frame(
nmlVar = c("Batch", "Mass", "Length", "Product","Batch", "Mass",
"Length", "Product", "Batch", "Mass", "Length", "Width", "Product"),
noFloat = c(254578, 20, 24, 24547, 254579, 23, 24, 24547, 254580, 20,
24, 19, 24547)
)
這里要注意的是在第三次重復中出現了新的可變寬度。 這對於我的數據集來說很典型,引入了新變量。 此處的關鍵指標是批處理,每次出現可變批處理時都應將其拆分。
樣本數據的dput輸出:
structure(list(nmlVar = structure(c(1L, 3L, 2L, 4L, 1L, 3L, 2L,
4L, 1L, 3L, 2L, 5L, 4L), .Label = c("Batch", "Length", "Mass",
"Product", "Width"), class = "factor"), noFloat = c(254578, 20,
24, 24547, 254579, 23, 24, 24547, 254580, 20, 24, 19, 24547)), .Names = c("nmlVar",
"noFloat"), row.names = c(NA, -13L), class = "data.frame")
這是您所追求的嗎?:
library(dplyr)
library(tidyr)
DFP %>%
mutate(sample = cumsum(nmlVar == 'Batch')) %>%
spread(nmlVar, noFloat)
得到:
sample Batch Length Mass Product Width 1 1 254578 24 20 24547 NA 2 2 254579 24 23 24547 NA 3 3 254580 24 20 24547 19
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.