g1 <- c(1,9,8,rep(5,5))
g2 <- c(2,3,4,4,4,3,3,4)
g3 <- c(3,11,6,7,5,6,6,6)
g4 <- c(4,8,6,6,7,5,5,5)
M <- as.data.frame(rbind(g1,g2,g3,g4))
colnames(M) <- c("grade", "2008", "2009", "2010", "2011", "2012", "2013", "2014")
g1 <- c(1, 0.1,0.15,rep(0.16,5))
g2 <- c(2, 0.3,0.4,0.4,0.4,0.3,0.3,0.4)
g3 <- c(3, 0.11,0.6,0.7,0.5,0.6,0.6,0.6)
g4 <- c(4, 0.8,0.6,0.6,0.7,0.5,0.5,0.5)
N <- as.data.frame(rbind(g1,g2,g3,g4))
colnames(N) <- c("grade", "2008", "2009", "2010", "2011", "2012", "2013", "2014")
这是M的样子
grade 2008 2009 2010 2011 2012 2013 2014
g1 1 9 8 5 5 5 5 5
g2 2 3 4 4 4 3 3 4
g3 3 11 6 7 5 6 6 6
g4 4 8 6 6 7 5 5 5
这就是N的样子
grade 2008 2009 2010 2011 2012 2013 2014
g1 1 0.10 0.15 0.16 0.16 0.16 0.16 0.16
g2 2 0.30 0.40 0.40 0.40 0.30 0.30 0.40
g3 3 0.11 0.60 0.70 0.50 0.60 0.60 0.60
g4 4 0.80 0.60 0.60 0.70 0.50 0.50 0.50
我想要的是一个新的数据框,它是使用上述两个数据框计算得出的。我已经使用以下代码获得了数据框:
var8a <- as.data.frame((matrix(NA, nrow=nrow(M), ncol= ncol(M)-1)))
for (i in 1:(nrow(M[,-1])-1)) {
for (j in 1:(ncol(M[,-1])-1)) {
var8a[i,j] = M[,-1][i+1,j+1]*(1-N[,-1][i+1,j+1])/M[,-1][i,j]
}
}
这是结果
V1 V2 V3 V4 V5 V6 V7
1 0.2666667 0.300 0.480 0.42 0.4200000 0.4800000 NA
2 0.8000000 0.525 0.625 0.60 0.8000000 0.8000000 NA
3 0.2181818 0.400 0.300 0.50 0.4166667 0.4166667 NA
4 NA NA NA NA NA NA NA
我的问题是,现在在M和N中,我只有一组,如果有多个组,我应该对代码做什么?
例如,它们是M和N
g1 <- c('a',1,9,8,rep(5,5))
g2 <- c('a',2,3,4,4,4,3,3,4)
g3 <- c('a',3,11,6,7,5,6,6,6)
g4 <- c('a',4,8,6,6,7,5,5,5)
g5 <- c('b',1,9,8,rep(5,5))
g6 <- c('b',2,3,4,4,4,3,3,4)
g7 <- c('b',3,11,6,7,5,6,6,6)
g8 <- c('b',4,8,6,6,7,5,5,5)
M <- as.data.frame(rbind(g1,g2,g3,g4,g5,g6,g7,g8))
colnames(M) <- c("country", "grade", "2008", "2009", "2010", "2011", "2012", "2013", "2014")
M
g1 <- c('a',1, 0.1,0.15,rep(0.16,5))
g2 <- c('a',2, 0.3,0.4,0.4,0.4,0.3,0.3,0.4)
g3 <- c('a',3, 0.11,0.6,0.7,0.5,0.6,0.6,0.6)
g4 <- c('a',4, 0.8,0.6,0.6,0.7,0.5,0.5,0.5)
g5 <- c('b',1, 0.1,0.15,rep(0.16,5))
g6 <- c('b',2, 0.3,0.4,0.4,0.4,0.3,0.3,0.4)
g7 <- c('b',3, 0.11,0.6,0.7,0.5,0.6,0.6,0.6)
g8 <- c('b',4, 0.8,0.6,0.6,0.7,0.5,0.5,0.5)
N <- as.data.frame(rbind(g1,g2,g3,g4,g5,g6,g7,g8))
colnames(N) <- c("country", "grade", "2008", "2009", "2010", "2011", "2012", "2013", "2014")
N
在这种情况下,如何将for循环应用于不同的国家?
非常感谢。
凯西