欲枢转result
列df
水平创建与一个单独的行的数据组为每 region
,state
,county
组合,其中列由year
然后city
排序。粘贴值
我也想找出新的数据通过region
,state
和county
设置每一行和删除四个results
列之间的空白。下面的代码完成了所有这些,但我怀疑它不是非常有效。
有没有办法做到这一点与reshape2
没有创建每个组的唯一标识符和每组内的编号观察?有没有办法使用apply来代替for循环来从矩阵中去除空白区域? (矩阵的使用方式不同于数学或编程结构。)我意识到这是两个不同的问题,也许我应该单独发布每个问题。
鉴于我可以达到预期的效果,并且只是希望改进代码,我不知道是否应该发布此代码,但我希望能够学习。感谢您的任何建议。
df <- read.table(text= "
region state county city year result
1 1 1 1 1 1
1 1 1 2 1 2
1 1 1 1 2 3
1 1 1 2 2 4
1 1 2 3 1 4
1 1 2 4 1 3
1 1 2 3 2 2
1 1 2 4 2 1
1 2 1 1 1 0
1 2 1 2 1 NA
1 2 1 1 2 0
1 2 1 2 2 0
1 2 2 3 1 2
1 2 2 4 1 2
1 2 2 3 2 2
1 2 2 4 2 2
2 1 1 1 1 9
2 1 1 2 1 9
2 1 1 1 2 8
2 1 1 2 2 8
2 1 2 3 1 1
2 1 2 4 1 0
2 1 2 3 2 1
2 1 2 4 2 0
2 2 1 1 1 2
2 2 1 2 1 4
2 2 1 1 2 6
2 2 1 2 2 8
2 2 2 3 1 3
2 2 2 4 1 3
2 2 2 3 2 2
2 2 2 4 2 2
", header=TRUE, na.strings=NA)
desired.result <- read.table(text= "
region state county results
1 1 1 1234
1 1 2 4321
1 2 1 0.00
1 2 2 2222
2 1 1 9988
2 1 2 1010
2 2 1 2468
2 2 2 3322
", header=TRUE, colClasses=c('numeric','numeric','numeric','character'))
# redefine variables for package reshape2 creating a unique id for each
# region, state, county combination and then number observations in
# each of those combinations
library(reshape2)
id.var <- df$region*100000 + df$state*1000 + df$county
obsnum <- sequence(rle(id.var)$lengths)
df2 <- dcast(df, region + state + county ~ obsnum, value.var = "result")
# remove spaces between columns of results matrix
# with a for-loop. How can I use apply to do this?
x <- df2[,4:(4+max(obsnum)-1)]
# use a dot to represent a missing observation
x[is.na(x)] = '.'
x.cat = numeric(nrow(x))
for(i in 1:nrow(x)) {
x.cat[i] = paste(x[i,], collapse="")
}
df3 <- cbind(df2[,1:3],x.cat)
colnames(df3) <- c("region", "state", "county", "results")
df3
df3 == desired.result
编辑:
马修伦德伯格的下面的答案是优秀的。之后,我意识到我还需要创建一个输出数据集,其中上面的四个结果列包含数字,有理数,并用空格分隔。所以,我已经发布了一个明显的方式来做到这一点,这改变了马修的答案。我不知道这是否是可以接受的协议,但是新的方案似乎与原始文章紧密相关,因此我认为我不应该发布新的问题。
谢谢你杰出的答案。后来我意识到我还需要一个输出数据集,其中四个结果列是数字的,并由空格分隔。我无法修改你的答案,但我靠近了,并在此发布了代码。 –