functional programming - append data to dataFrame in R function -
i trying write r function adds new row existing dataframe.
here code (r newbie here):
qrows <- data.frame( rowquery = character(0), "backtest p&l" = character(0), stringsasfactors=false) # add row dataframe qrows[nrow(qrows) + 1, ] <- c("sp500(vwpc) | abc(30) | qcume", "12%") #define function add new row dataframe q <- function(data, y){ data[nrow(data) + 1, ] <- c(y,"88") } # run new function q(qrows, "newquery") #examine output: no new row added qrows
the code runs without error, no new row added.
two changes :
you need return function output , assign outputted value qrows.
qrows <- data.frame( rowquery = character(0), "backtest p&l" = character(0), stringsasfactors=false) # add row dataframe qrows[nrow(qrows) + 1, ] <- c("sp500(vwpc) | abc(30) | qcume", "12%") #define function add new row 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 qrows** qrows
output
rowquery backtest.p.l 1 sp500(vwpc) | abc(30) | qcume 12% 2 newquery 88
in code, q added new row data
.
note, new row added variable data
local function q
, not qrows
.
Comments
Post a Comment