【问题标题】:append data to dataFrame in R function将数据附加到R函数中的dataFrame
【发布时间】:2016-04-27 09:54:34
【问题描述】:

我正在尝试编写一个将新行添加到现有数据帧的 R 函数。

这是我的代码(这里是 R 新手):

    qRows <- data.frame( RowQuery = character(0), "BackTest P&L" = character(0), stringsAsFactors=FALSE)
    # add row to dataFrame
    qRows[nrow(qRows) + 1, ] <- c("sp500(vwpc) | abc(30) | qcume",  "12%")

    #define function to add new row to dataFrame
    Q <- function(data, y){
      data[nrow(data) + 1, ] <- c(y,"88")
    }
    # run new function
    Q(qRows, "newQuery")
    #examine output: but no new row added
    qRows

代码运行没有错误,但没有添加新行。

【问题讨论】:

  • 您可以在函数末尾添加return(data)
  • 是的,这行得通。但后来我不得不写:qRows = Q(qRows, "xyz")。我希望避免这种情况,但在网上没有找到任何可以让我知道如何做到这一点的线索。

标签: r functional-programming dataframe


【解决方案1】:

两个变化:

你需要返回函数输出,然后将输出的值赋回给qrows。

qRows <- data.frame( RowQuery = character(0), "BackTest P&L" = character(0), stringsAsFactors=FALSE)
# add row to dataFrame
qRows[nrow(qRows) + 1, ] <- c("sp500(vwpc) | abc(30) | qcume",  "12%")

#define function to add new row to dataFrame
Q <- function(data, y){
  data[nrow(data) + 1, ] <- c(y,"88")
  return(data)    # <---------------------------------**return data**
}
# run new function
qRows= Q(qRows, "newQuery")  #<---------------------  **assign output to qRows**
qRows

输出

                       RowQuery BackTest.P.L
1 sp500(vwpc) | abc(30) | qcume          12%
2                      newQuery           88

在您的代码中,Q 向 data 添加了一个新行。

请注意,新行已添加到变量 data 中,该变量是函数 Q 的本地变量,而不是 qRows

【讨论】:

  • 最后一行被视为返回对象。缺少的部分是作业。
  • 这里显示了我的 R 经验不足。那么有没有办法通过引用来传递dataFrame,从而让对数据所做的更改持续存在呢?或者这可能只是一个坏主意,并且违背了良好的 R 最佳实践?
  • 供将来参考:我可以通过添加分配语句来更改 Q 函数中的 qRows:Q
【解决方案2】:
> #define function to add new row to dataFrame
> Q <- function(data, y){
+     nms <- names(data)
+     dat <- rbind(data, t(c('sp500(vwpc) | abc(30) | qcume','12%')), t(c(y,'88')))
+     names(dat) <- nms
+     return(dat)
+     }
>
> # run new function
> Q(qRows,'newQuery')
                       RowQuery BackTest.P.L
1 sp500(vwpc) | abc(30) | qcume          12%
2                      newQuery           88

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 2018-11-24
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2022-01-28
    相关资源
    最近更新 更多