【发布时间】:2015-04-30 16:59:06
【问题描述】:
我在多个单独的 csv 文件中有数据,我想为每个文件创建一个带有一行的 data.frame。下面的函数提供要用于每一行的数据。我不想更改此代码,例如包含输出向量的农场部分。
vectorfromfile <- function(farmid) {
# Reads data from a file named farm{id}.csv, eg
# farm001.csv, and returns one named vector
# of length two with class numeric and names 'apples'
# and 'oranges' An example could be c(apples=4, oranges=6)
# The line below is a dummy for test purposes
c(apples=farmid+1000, oranges=farmid+2000)
}
然后我有一个向量,farmids,例如farmids
> data.frame(id=c(1,3,5), apples=c(4,2,3), oranges=c(6,5,2) )
id apples oranges
1 1 4 6
2 3 2 5
3 5 3 2
我找到了几种方法来做到这一点,所有这些方法都非常丑陋并且占用了很多行。但我想以最优雅的方式做到这一点,使用 split-apply-combine 方法。所以我希望我可以简单地应用于(迭代)一个向量,并得到一个 data.frame 作为结果。类似的东西
apply(farmids, ???? ) # farmids is a vector
这可能吗?如果不是,那么也许迭代具有相同值的列表?如果即使那是不可能的,那将是最优雅的方式。
下面我的丑陋尝试
vect2df_v1 <- function(farmids=c(1,3,5)) {
df <- data.frame(id=farmids, apples=rep(NA, length(farmids)), oranges=rep(NA, length(farmids)))
for (i in 1:length(farmids)) {
df[i, c('apples', 'oranges')] <- vectorfromfile(df[i, 'id'])
}
df
}
vect2df_v2 <- function(farmids=c(1,3,5)) {
# Obviously it could be written into one (even uglier) line
farmrow <- function(farmid) { c(farmid, vectorfromfile(farmid)) }
lst <- lapply(farmids, farmrow)
mtrx <- matrix(unlist(lst), ncol=3, byrow=T, dimnames=list(NULL,c('id', 'apples','oranges')))
data.frame(mtrx)
}
【问题讨论】: