abel
曾经写过一个R中数据操作的的笔记,觉得其中多选题编码形式之间的转化比较有用
下面这个函数效率不是很高,数据量不是太大的时候倒是可以用
# 将记录题项形式的多选题变成0、1编码形式
# 主要使用S中方便的索引运算功能
mult.choice <- function(da, items=NULL)
{
value.max <- max(da)
ans <- as.data.frame(matrix(0, ncol=value.max, nrow=nrow(da)))
da <- as.matrix(da)
for(i in 1:nrow(da)) ans[i, unique(da[i, ])] <- 1
if(is.null(items)) items <- 1:value.max
if(max(items) > value.max) items <- intersect(items, 1:value.max)
ans <- as.data.frame(ans[, items])
names(ans) <- paste('V', items, sep='.')
ans
}
# for example
da <- as.data.frame(matrix(rpois(1000, lambda=1)+1, ncol=4))
mult.choice(da)
mult.choice(da, items=c(1, 3, 5))
能处理的需要是编码为正整数的才成,如果不是正整数,需要重新编码下;recode以后,也可以相应提高不少效率,这主要事针对数据框或者矩阵取行列而言,需要花费时间和空间
yihui
Thanks! 程序主要的一句就是for(i in 1:nrow(da)) ans[i, unique(da[i, ])] <- 1,意即:若选择了多选题的第j项,那么就将第j个变量赋值为1。
sociology
for 太慢了,你例子中的数据那么小已经明显感觉到了慢。
来一个快一点的。
mult.choice2 <- function(da, items=NULL)
## 2007,05,06
## by ronggui.huang@gmail.com
{
if (is.null(items)) items <- sort(unique(unlist(lapply(da,unique))))
nitems <- length(items)
ans <- matrix(0, ncol=nitems, nrow=nrow(da))
ind <- t(apply(da,1,function(x) items %in% x))
ans[ind]<-1
ans <- as.data.frame(ans)
names(ans) <- paste('V', items, sep='.')
ans
}
[quote]引用第0楼abel于2007-05-05 16:03发表的“R中多选题的一个处理”:
曾经写过一个R中数据操作的的笔记,觉得其中多选题编码形式之间的转化比较有用
下面这个函数效率不是很高,数据量不是太大的时候倒是可以用
# 将记录题项形式的多选题变成0、1编码形式
.......[/quote]
nous
嗯,尽量避免用循环