![](/img/trans.png)
[英]R: How to apply a function to a data frame to make plots of each subset with a unique factor combination
[英]How to make each unique observation a factor w/ a binary response in R?
我有一個像這樣的數據集:
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
}
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
此解決方案使用ddply
form plyr,但是任何類似的split-apply-combine工具都可以使用相同的基本組件:
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
內部可能采用的唯一值進行硬編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.