0

我有一个数据集,如:

id   region
 1     2
 1     3
 2     1
 3     4
 3     5

我想创建一个数据集,如:

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

我一直在使用一个手写循环,每次都会创建一个因子 regionN,但我希望有某种方法可以自动化这个过程。

我也尝试了以下失败的方法。

n <- 1
while(n <= nrow(region_list))  {
  paste("R",as.character(region_list$region_id[n])) <- subset(region_list, region_list$region_id == n)
  n <- n + 1
}
4

2 回答 2

1
DF <- data.frame(id = c(1,1,2,3,3), region = c(2,3,1,4,5))
DM <- table(DF)
DM
#   region
#id  1 2 3 4 5
#  1 0 1 1 0 0
#  2 1 0 0 0 0
#  3 0 0 0 1 1
is.matrix(DM)
#[1] TRUE

require(reshape)
DF2 <- cast(data.frame(DM),id~region)
names(DF2)[-1] <- paste("region",names(DF2)[-1],sep="")
DF2
#  id region1 region2 region3 region4 region5
#1  1       0       1       1       0       0
#2  2       1       0       0       0       0
#3  3       0       0       0       1       1
于 2012-07-21T08:47:56.407 回答
0

此解决方案使用ddply表单plyr,但任何类似的拆分应用组合工具都可以使用相同的基本部分:

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

dat$region <- factor(dat$region)

foo <- function(x){
    res <- as.integer(levels(x$region) %in% x$region)
    names(res) <- paste0("region",1:5)
    res
}

ddply(dat,.(id),.fun = foo)
   id region1 region2 region3 region4 region5
1  1       0       1       1       0       0
2  2       1       0       0       0       0
3  3       0       0       0       1       1

你可以绕过转换region为一个因子,但我认为你必须硬编码它可能在foo.

于 2012-07-21T02:10:03.017 回答