use*_*719 4 casting r reshape dataframe
我正在尝试创建一个具有二元响应且已使用强制转换的因子列表.
DF2 <- cast(data.frame(DM), id ~ region)
names(DF2)[-1] <- paste("region", names(DF2)[-1], sep = "")
Run Code Online (Sandbox Code Playgroud)
我得到的问题是答案是答案出现的频率,而我正在寻找它是否匹配.
例如,我有:
id region
1 2
1 3
2 2
3 1
3 1
Run Code Online (Sandbox Code Playgroud)
我想要的是:
id region1 region2 region3
1 0 1 1
2 0 1 0
3 1 0 0
Run Code Online (Sandbox Code Playgroud)
我有点喜欢dcast从reshape2:
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
Run Code Online (Sandbox Code Playgroud)
可能有一种更顺畅的方法可以做到这一点,但我会说实话,我不会经常抛出一些东西.
原始数据:
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
Run Code Online (Sandbox Code Playgroud)
将数据分组:
aggregate(model.matrix(~ region - 1, data=x), x["id"], max)
Run Code Online (Sandbox Code Playgroud)
结果:
id region1 region2 region3
1 1 0 1 1
2 2 0 1 0
3 3 1 0 0
Run Code Online (Sandbox Code Playgroud)