的一種方法是分配自己儘可能多行的矩陣在數據幀中的最高值,然後在正確使用一個簡單的循環來填補它與1
小號位置。
我們調用分配的矩陣output
,給它與原始數據幀相同的colname。
max.value <- max(df, na.rm=T)
output <- matrix(0, nrow = max.value, ncol=ncol(df))
colnames(output) <- colnames(df)
現在我們有一個6x3的零矩陣。現在,一個簡單的嵌套循環遍歷output
的每列,將1分配給output
的適當列位置,如i
所示。
for (j in 1:ncol(output)) { #for each column of the output matrix
for (i in df[, j]) { #for the appropriate position in the column according to df
output[i, j] <- 1 #assign 1 to that position
}
}
> output
person1 person2 person3
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 0
[4,] 1 1 0
[5,] 0 0 1
[6,] 1 0 0
應該儘可能多的人和你需要的行。
附錄:這裏是測試數據幀的dput
。
structure(list(person1 = c(1L, 4L, 6L), person2 = c(2L, 4L, NA
), person3 = c(NA, 5L, NA)), .Names = c("person1", "person2",
"person3"), class = "data.frame", row.names = c(NA, -3L))
來源
2016-11-29 19:25:38
Joe
我想你希望把1對其中行號表示該列的行,這是不一樣的*包含在每一行* – Psidom