我在 R 中做了很多努力才能做到這一點。我的資料看起來像這樣(真實資料有超過 12 萬個觀察值):
df <- data.frame(
Input = c(1,2,3,4,4,5,1,3,4),
Output = c(91,91,91,91,91,91,92,92,92)
)
df
Input Output
1 1 91
2 2 91
3 3 91
4 4 91
5 4 91
6 5 91
7 1 92
8 3 92
9 4 92
數字是物理東西的代碼。這里的關鍵是產品 91 使用 5 個輸入,而產品 92 僅使用 3 個,并且 91 中有重復項(兩個 4)
我希望資料框將輸出作為列名,將輸入作為值(不考慮重復項):
91 92
1 1
2 NA
3 3
4 4
5 NA
所以,我使用了從長到寬的重塑
df2 <- reshape(df, idvar = "Input", v.names = "Output", timevar = "Output", direction = "wide", sep = "_")
這需要很多時間,并且無法使這篇文章中的其他代碼起作用。它產生一個中間步驟:
Input Output_91 Output_92
1 1 91 92
2 2 91 NA
3 3 91 92
4 4 91 92
5 5 91 NA
然后,我所要做的就是用第一列替換每個輸出列,除非是 NA。我可以一次為一列輕松完成此操作。例如:
df2$Output_92[!is.na(df2$Output_92)] <- df2$Input[!is.na(df2$Output_92)]
我一直在嘗試對列進行回圈以遍歷所有 2 列,模仿上述命令。就像是:
for(i in colnames(df2)){
df2[!is.na(i)][i] <- df2$Input[!is.na(i)][i]
}
This does not work.
So, in principle I need help either only in this loop (title of question). But hints optimising the reshaping, or perhaps a simpler way to do the whole thing are more than welcome.
UPDATE: I realised duplicates was key to my problem, since without these, standard solutions in the linked post work fine. Updated question accordingly. The answer below helps with cases where ID has duplicates.
uj5u.com熱心網友回復:
如果您對給定的輸出有重復的輸入,那么假設您不關心對它們進行計數或以任何不同的方式對待它們,那么下面的所有方法都可以通過替換df為unique(df). (dplyr::distinct如果愿意,也可以使用。)
一旦你解決了唯一性,那么......這就是從長到寬的“只是”重塑/旋轉。
基數R
stats::reshape使用起來有點困難,它需要一些不是唯一存在的東西。例如,它需要idvar和v.names變數是唯一的列(所以我們重復Input):
df$Input2 <- df$Input
out <- reshape(unique(df), idvar = "Input", v.names = "Input2", timevar = "Output", direction = "wide")
out
# Input Input2.91 Input2.92
# 1 1 1 1
# 2 2 2 NA
# 3 3 3 3
# 4 4 4 4
# 6 5 5 NA
names(out) <- gsub("Input2\\.", "", names(out))
# out[,-1]
91 92
# 1 1 1
# 2 2 NA
# 3 3 3
# 4 4 4
# 6 5 NA
整理
(重復列同上。)
library(dplyr)
library(tidyr) # pivot_wider
df %>%
distinct() %>%
mutate(Input2 = Input) %>%
pivot_wider(Input, names_from = "Output", values_from = "Input2") %>%
select(-Input)
# # A tibble: 5 x 2
# `91` `92`
# <dbl> <dbl>
# 1 1 1
# 2 2 NA
# 3 3 3
# 4 4 4
# 5 5 NA
資料表
"Input2"這里不需要這樣的要求。
library(data.table)
dcast(unique(as.data.table(df)), Input ~ Output, value.var = "Input")[,-1]
# 91 92
# <num> <num>
# 1: 1 1
# 2: 2 NA
# 3: 3 3
# 4: 4 4
# 5: 5 NA
在這里,unique可進可出as.data.table(.),任君選擇。
uj5u.com熱心網友回復:
簡單地說,因為我對重復項不感興趣,所以我只需要事先洗掉它們,之后這篇文章中的代碼就可以正常作業了。
洗掉 df <- df[!duplicated(df[c("Output","Input")]),]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325703.html
上一篇:按組匯總跨多個函式的多列
下一篇:有沒有辦法在合并函式中使用向量?
