借助for循环函数创建表

时间:2015-09-27 14:32:42

标签: r

我正在尝试设计for loop,这将返回我的表的第2行和第3行的差异,但是无论我做什么,for循环都会返回非常大的表或NA。如何修改for循环?与最终结果一样,将返回与cbind(a.trade, b.trade, c.trade, d.trade, f.trade, g.trade, h.trade, l.trade, m.trade, n.trade, r.trade)相同的结果。谢谢

a<- read.csv("2003.csv", header=TRUE)
b<- read.csv("2004.csv", header=TRUE, na.strings='             -')
c<- read.csv("2005.csv", header=TRUE)
d<- read.csv("2006.csv", header=TRUE)
f<- read.csv("2007.csv", header=TRUE)
g<- read.csv("2008.csv", header=TRUE)
h<- read.csv("2009.csv", header=TRUE)
l<- read.csv("2010.csv", header=TRUE)
m<- read.csv("2011.csv", header=TRUE)
n<- read.csv("2012.csv", header=TRUE)
r<- read.csv("2013.csv", header=TRUE)

a.trade <- a$Exports- a$General.Imports
b.trade <- b$Exports- b$General.Imports
c.trade <- c$Exports- c$General.Imports
d.trade <- d$Exports- d$General.Imports
f.trade <- f$Exports- f$General.Imports
g.trade <- g$Exports- g$General.Imports
h.trade <- h$Exports- h$General.Imports
l.trade <- l$Exports- l$General.Imports
m.trade <- m$Exports- m$General.Imports
n.trade <- n$Exports- n$General.Imports
r.trade <- r$Exports- r$General.Imports
cbind(a.trade, b.trade, c.trade, d.trade, f.trade,
 g.trade, h.trade, l.trade, m.trade, n.trade, r.trade)


for (i in 2:55, i+5) {
x<-c(a,b,c,d,f,g,h,l,m,n,r)
v<-cbind(x[[i+1]]-x[[i+2]])
print(v)
}

1 个答案:

答案 0 :(得分:0)

data_frame(year = 2003:2013) %>%
    group_by(year) %>%
    do("%s.csv" %>%
        sprintf(.$year) %>%
        read.csv) %>%
    mutate(trade = Exports - Imports) %>%
    group_by(year) %>%
    summarize(difference = trade[3] - trade[2])