想象一下,你有五个国家在十年内的表现得分。您确实知道,某些国家/地区的表现在特定年份发生了很大变化。现在,您想知道它们的变化是积极的还是消极的。正是这最后一步让我感到困扰。
样本数据:
mydata<-1:3
mydata<-expand.grid(
country=c('A', 'B', 'C', 'D', 'E'),
year=c('1980','1981','1982','1983','1984','1985','1986','1987','1988','1989'))
mydata$score=sapply(runif(50,0,2), function(x) {round(x,4)})
library(reshape)
mydata<-reshape(mydata, v.names="score", idvar="year", timevar="country", direction="wide")
变更识别:
score.cols <- grep("score", colnames(mydata), value=TRUE)
period.cols <- gsub("score", "period", score.cols)
compute.period <- function(x)as.integer(c(NA, abs(diff(x)) >= 0.5))
cbind(mydata, `names<-`(lapply(mydata[score.cols], compute.period), period.cols))
> cbind(mydata, `names<-`(lapply(mydata[score.cols], compute.period), period.cols))
year score.A score.B score.C score.D score.E period.A period.B period.C period.D period.E
1 1980 0.4029 0.3308 1.0432 0.7405 0.7254 NA NA NA NA NA
6 1981 1.7577 0.5479 1.4437 1.3996 0.8454 1 0 0 1 0
11 1982 1.9603 0.5404 1.2687 1.4317 0.0203 0 0 0 0 1
16 1983 0.5509 1.5834 1.3954 0.4935 0.4994 1 1 0 1 0
21 1984 1.9672 1.0628 1.8436 0.4327 0.0144 1 1 0 0 0
26 1985 1.6799 1.5873 0.5898 0.9553 1.3475 0 1 1 1 1
31 1986 1.2918 1.7049 0.3448 0.1841 0.9270 0 0 0 1 0
36 1987 0.1719 0.3297 0.6386 0.4075 1.8494 1 1 0 0 1
41 1988 0.7123 1.2378 0.9220 0.3278 1.5888 1 1 0 0 0
46 1989 0.2998 0.4418 1.0640 1.1405 0.7034 0 1 0 1 1
识别变化方向:
direct.cols<-gsub("score", "direction", score.cols)
compute.direction<-function(mydata){
for (i in 1:length(score.cols))
{
direct.cols[,i] <- ifelse((period.cols[i] == 1) & (score.cols[i] >= score.cols[i-1]), 1,
+ ifelse((period.cols[i] == 1) & (score.cols[i] <= score.cols[i-1]), 2,
+ ifelse((period.cols[i] != 1), 0, NA)))
}}
cbind(mydata, `names<-`(lapply(mydata[score.cols], compute.direction), direct.cols))
问题: 运行最后一步时,我收到以下错误消息:
Error in direct.cols[, i] <- ifelse((period.cols[i] == 1) & (score.cols[i] >= :
incorrect number of subscripts on matrix
为什么?我做错了什么?
任何帮助将不胜感激。太感谢了。
这个问题建立在flodel和Maiasaura对我之前提出的问题[https://stackoverflow.com/questions/12443202/how-to-get-the-difference-in-value-between-subsequent-observations-国年] .