【问题标题】:Creating a data.frame with rows from a function that returns vectors从返回向量的函数中创建包含行的 data.frame
【发布时间】: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)
}

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    do.call(rbind, ...) 很简单。

    你可以这样写你的vect2df

    vect2df <- function(vec) {
      data.frame(id = vec, do.call(rbind, lapply(vec, vectorfromfile)))
    } 
    

    演示:

    vect2df(c(1, 3, 5))
    #   id apples oranges
    # 1  1   1001    2001
    # 2  3   1003    2003
    # 3  5   1005    2005
    

    当然,这一切都可以直接使用within 完成(如果vectorfromfile 不是关键函数,但可以简单定义。

    例子:

    within(data.frame(id = c(1, 3, 5)), {
      oranges <- id + 2000
      apples <- id + 1000
    })
    #   id apples oranges
    # 1  1   1001    2001
    # 2  3   1003    2003
    # 3  5   1005    2005
    

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 2018-12-05
      • 2018-07-01
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多