[英]Split dataframe array column into multiple binary columns [R]
數組列是當前的,其他列是目標
我有一列 arrays ,我想將其拆分為多個二進制文件。 我已經使用創建了所有列
dat[,unique(unlist(df$array_column))] = 0
我嘗試使用ifelse
語句然后根據需要將列設置為 '1' 但是使用%in%
不適用於ifelse
。 我可以創建一個嵌套的 for 循環,但是我有數百萬行並且正在尋找比這更快的解決方案。
testdf = data.frame('a'=c(1,2,3,4,5),'array_column'=c('a-b-c','b-a','c-d','d-e-e','e-a'),stringsAsFactors = F)
testdf$array_column = strsplit(testdf$array_column,'-')
我認為問題在於如何將向量列表轉換為二進制矩陣/data.frame
這是一個解決方案
testdf = data.frame('a'=c(1,2,3,4,5),'array_column'=c('a-b-c','b-a','c-d','d-e-e','e-a'),stringsAsFactors = F)
testdf$array_column = strsplit(testdf$array_column,'-')
library('plyr')
# Creates a list of data.frames with 1s for each value observed
binary <- lapply(testdf$array_column, function(x) {
vals <- unique(x)
x <- setNames(rep(1,length(vals)), vals);
do.call(data.frame, as.list(x))
})
# Joins into single data.frame
result <- do.call(rbind.fill, binary)
result[is.na(result)] <- 0
result
# a b c d e
# 1 1 1 1 0 0
# 2 1 1 0 0 0
# 3 0 0 1 1 0
# 4 0 0 0 1 1
# 5 1 0 0 0 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.