分类变量向量到矩阵中

时间:2015-06-15 18:51:58

标签: r

我有一个具有唯一ID和分类变量的数据框。我需要将所有唯一ID折叠成一行,将所有适用的分类变量折叠成不同的向量,这样我就可以用一个矩阵来进行某些回归分析。例如:

id    cat
1     a
2     b
1     b
3     c
4     a
2     a
4     c
3     c

output:
id   cat.a   cat.b   cat.c
1    1       1       0
2    1       1       0
3    0       0       2
4    1       0       1

我在有用的包中查看了build.x函数,但无法解决折叠为单个id的问题

2 个答案:

答案 0 :(得分:2)

这看起来像重塑数据

library(reshape2)
dcast(df, id ~ cat)

# Using cat as value column: use value.var to override.
# Aggregation function missing: defaulting to length
#   id a b c
# 1  1 1 1 0
# 2  2 1 1 0
# 3  3 0 0 2
# 4  4 1 0 1

虽然这对于这样一个简单的问题可能有点过头了。正如@Seth在评论中指出的那样,您可以使用table

with(df, table(id, cat))
#    cat
# id  a b c
#   1 1 1 0
#   2 1 1 0
#   3 0 0 2
#   4 1 0 1

(使用此数据:)

df = structure(list(id = c(1L, 2L, 1L, 3L, 4L, 2L, 4L, 3L), cat = structure(c(1L, 
2L, 2L, 3L, 1L, 1L, 3L, 3L), .Label = c("a", "b", "c"), class = "factor")), .Names = c("id", 
"cat"), class = "data.frame", row.names = c(NA, -8L))

答案 1 :(得分:0)

我认为这可以在不使用任何必需库的情况下完成您正在寻找的内容 - 尽管它确实使用了两个嵌套循环,因此它可能很慢。

## setting up the data you gave as an example in your question
dat=matrix(c(1,2,1,3,4,2,4,3,'a','b','b','c','a','a','c','c'),ncol=2)
data=data.frame(dat)

## determine the categories as defined by your data 
cats <- levels(data$X2)

## create a blank matrix
out=matrix(0,nrow=length(levels(data$X1)),ncol=length(levels(data$X2)))

## what is the lowest value of your first column
i=min(as.numeric(data$X1))

## j will serve as a counter for the rows in the out matrix
j=1
while(i<=max(as.numeric(data$X1)))
    {
        ## find the unique values associated with the first 'i' 
        idi <- which(as.numeric(data$X1)==i)
        ## set up a counter that corresponds to the columns of your out matrix
        k=1
        while(k<= length(cats)) {
            ## determine the values associated with the particular category 
            out[j,k] <- length(which(data[idi,2]==cats[k]))
            k=k+1
        }
        i=i+1
        j=j+1
    }