如何使用强制转换或其他函数在R中创建二进制表

时间:2012-07-25 21:46:08

标签: r dataframe casting reshape

我正在尝试创建一个具有二元响应且已使用强制转换的因子列表。

DF2 <- cast(data.frame(DM), id ~ region)
names(DF2)[-1] <- paste("region", names(DF2)[-1], sep = "")

我得到的问题是答案是答案出现的频率,而我正在寻找它是否匹配。

例如我有:

id region
 1   2
 1   3
 2   2
 3   1
 3   1

我想要的是:

id region1 region2 region3
1   0          1     1
2   0          1     0
3   1          0     0

4 个答案:

答案 0 :(得分:7)

我更喜欢 reshape2 :{/ p>中的dcast

library(reshape2)
dat <- read.table(text = "id region
 1   2
 1   3
 2   2
 3   1
 3   1",header = TRUE,sep = "")

dcast(dat,id~region,fun.aggregate = function(x){as.integer(length(x) > 0)})

  id 1 2 3
1  1 0 1 1
2  2 0 1 0
3  3 1 0 0

可能有一种更顺畅的方法可以做到这一点,但我会说实话,我不会经常抛出一些东西。

答案 1 :(得分:4)

这是使用table在一行中执行此操作的“棘手”方法(括号很重要)。假设您的data.frame名为df

(table(df) > 0)+0
#    region
# id  1 2 3
#   1 0 1 1
#   2 0 1 0
#   3 1 0 0

table(df) > 0为我们提供TRUEFALSE;添加+0会将TRUEFALSE转换为数字。

答案 2 :(得分:3)

原始数据:

x <- data.frame(id=c(1,1,2,3,3), region=factor(c(2,3,2,1,1)))

> x
  id region
1  1      2
2  1      3
3  2      2
4  3      1
5  3      1

对数据进行分组:

aggregate(model.matrix(~ region - 1, data=x), x["id"], max)

结果:

  id region1 region2 region3
1  1       0       1       1
2  2       0       1       0
3  3       1       0       0

答案 3 :(得分:1)

不需要专门的功能:

x <- data.frame(id=1:4, region=factor(c(3,2,1,2)))
x
   id region
1  1      3
2  2      2
3  3      1
4  4      2

x.bin <- data.frame(x$id, sapply(levels(x$region), `==`, x$region))
names(x.bin) <- c("id", paste("region", levels(x$region),sep=''))
x.bin

  id region1 region2 region3
1  1   FALSE   FALSE    TRUE
2  2   FALSE    TRUE   FALSE
3  3    TRUE   FALSE   FALSE
4  4   FALSE    TRUE   FALSE

或者对于整数结果:

x.bin2 <- data.frame(x$id,  
    apply(sapply(levels(x$region), `==`, x$region),2,as.integer)
) 
names(x.bin2) <- c("id", paste("region", levels(x$region),sep=''))
x.bin2


  id region1 region2 region3
1  1       0       0       1
2  2       0       1       0
3  3       1       0       0
4  4       0       1       0