※ 引述《Udyr (Udyr)》之铭言:
: [问题类型]:
: 程式咨询(我想用R 做某件事情,但是我不知道要怎么用R 写出来)
: [软件熟悉度]:
: 请把以下不需要的部份删除
: 入门(写过其他程式,只是对语法不熟悉)
: [问题叙述]:
: 资料形式为list
: $`875523`
: [1] "A" "B" "E" "C" "D" "G"
: $`881823`
: [1] "B" "D" "F" "E"
: 想将资料整理为以下格式
: A B C D E F G
: 875523 1 1 1 1 1 0 1
: 881823 0 1 0 0 1 1 0
A_list = list(LETTERS[c(1,2,5,3,4,7)], LETTERS[c(2,4,6,5)])
names(A_list) = c("875523", "881823")
all_levels = sort(unique(unlist(A_list)))
out = sapply(A_list, function(x) {
tmp = rep(0, length(all_levels))
tmp[match(x, all_levels)] = 1
tmp
})
out = t(out)
colnames(out) = all_levels
out
## A B C D E F G
## 875523 1 1 1 1 1 0 1
## 881823 0 1 0 1 1 1 0
## 如果A, B, C, ...不是只有一个,sapply内部要做更改
out = sapply(A_list, function(x) {
x2 = tapply(rep(1,length(x)), x, sum)
tmp = rep(0, length(all_levels))
tmp[match(names(x2), all_levels)] = x2
tmp
})
## method 2 (可以查看前面的资料整理套件介绍的系列文)
library(reshape2)
library(data.table)
library(plyr)
library(dplyr)
library(magrittr)
A_list = list(LETTERS[c(1,2,5,3,4,7)], LETTERS[c(2,4,6,5)])
names(A_list) = c("875523", "881823")
DT = llply(1:length(A_list), function(i){
data.table(id = names(A_list)[i], level = A_list[[i]])
}) %>% bind_rows
DT %>% dcast(id ~ level)
## id A B C D E F G
## 1 875523 1 1 1 1 1 0 1
## 2 881823 0 1 0 1 1 1 0
## use sparse matrix
library(Matrix)
A_list = list(LETTERS[c(1,2,5,3,4,7)], LETTERS[c(2,4,6,5)])
names(A_list) = c("875523", "881823")
all_levels = sort(unique(unlist(A_list)))
j_index = lapply(A_list, match, table = all_levels)
i_index = lapply(1:length(out), function(x) rep(x, length(out[[x]])))
i_index = as.integer(unlist(i_index)-1)
j_index = as.integer(unlist(j_index)-1)
out = new("dgTMatrix", i = i_index, j = j_index,
x=rep(1,length(i_index)),
Dim=c(length(A_list), length(all_levels)))
如果是all_levels无法配置足够的内存的话
请使用循环用setdiff做人工的unique...
这里没考虑大于1的可能性,如果大于1需要比较复杂的运算