如何将相同的代码应用于R中的多个对象

时间:2015-04-13 13:41:41

标签: r

我有一些数据框包含相同数量的列,并命名为mydf1mydf10并想要聚合,与包含完整日期的数据框合并,将缺少的日期替换为0,并与另一列合并。以下代码显示了我在一个数据框上工作的步骤。

### Aggregate id and count occurrences
mydf0_1 <- aggregate(id ~ date,data = mydf0,FUN=length)

## rename second column
names(mydf0_1) [2] <- "count"

## Create a full data frame of date
nn <- data.frame(date = seq(as.Date("2000-01-01"), as.Date("2005-12-31"),
                            by="days"))

###  Merge the data with a full series
res <- merge(mydf0_1,nn,by.x='date',by.y='date',all.x=T,all.y=T)

## Replace NA with 0 count
res$count[is.na(res$count)] <- 0

## merge with another data frame 
st0 <- cbind(res, temp)

我如何自动执行该流程并将相同的脚本应用于mydf0mydf10的所有数据框?

其中一个数据框如下:

> dput(mydf0)
structure(list(id = c(285476L, 107062L, 138919L, 88350L, 71678L, 
226406L, 122913L, 36801L, 37201L, 83417L), date = structure(c(10957, 
10957, 10957, 10957, 10957, 10957, 10957, 10958, 10958, 10958
), class = "Date")), datalabel = "", time.stamp = "13 Apr 2015 15:20", .Names = c("id", 
"date"), formats = c("%9.0g", "%td"), types = c(253L, 255L), val.labels = c("", 
""), var.labels = c("", ""), expansion.fields = list(c("_dta", 
"_lang_c", "default"), c("_dta", "_lang_list", "default")), row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10"), version = 12L, class = "data.frame")

1 个答案:

答案 0 :(得分:3)

我们可以将data.frame放在一个列表(mget(paste0('mydf', 0:10)))中并应用代码。

  nn<- data.frame(date=seq(as.Date("2000-01-01"),
                       as.Date("2005-12-31"), by="days"))
  lst <- lapply(mget(paste0('mydf',0:10)), function(x) {
           d1 <- aggregate(cbind(count=id)~date, x, FUN=length)
           res <- merge(d1, nn, by='date', all=TRUE)
           res$count[is.na(res$count)] <- 0
           merge(res, temp, by='date', all=TRUE)
         })

注意:帖子中未定义temp对象。