Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R函数中将数据追加到数据帧_R_Functional Programming_Dataframe - Fatal编程技术网

在R函数中将数据追加到数据帧

在R函数中将数据追加到数据帧,r,functional-programming,dataframe,R,Functional Programming,Dataframe,我正在尝试编写一个R函数,将新行添加到现有数据帧中 这是我的代码(这里是R新手): qRows两个变化: 您需要返回函数输出,然后将输出值分配回qrows qRows <- data.frame( RowQuery = character(0), "BackTest P&L" = character(0), stringsAsFactors=FALSE) # add row to dataFrame qRows[nrow(qRows) + 1, ] <- c("sp500(v

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

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


qRows两个变化:

您需要返回函数输出,然后将输出值分配回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
在代码中,Q向
数据添加了一个新行

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

\define函数将新行添加到数据帧
> #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

>Q您可以在函数末尾添加
return(data)
。是的,可以。但是我必须写:qRows=Q(qRows,xyz)。我希望避免这种情况,但在网上没有找到任何线索,告诉我如何做到这一点。最后一行被视为返回对象。缺少的部分是作业。我的经验不足在这里表现出来。所以没有办法通过引用传递数据帧,所以对数据所做的更改会持久化吗?或者这可能只是一个坏主意,与良好的R最佳实践背道而驰?供将来参考:我可以通过添加assign语句来更改Q函数中的qRows:Q
                       RowQuery BackTest.P.L
1 sp500(vwpc) | abc(30) | qcume          12%
2                      newQuery           88
> #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