Context
As a followup to R: Pass data.frame by reference to a function and How to add a column in the data frame within a function
I am attempting the following, seemingly easy, function:
naToZero <- function(df) {
df$Vol[is.na(df$Vol)] <- 0
}
Data.frame
> str(WFM)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 990571 obs. of 14 variables:
$ Date : chr "04/12/2017" "04/12/2017" "04/12/2017" "04/12/2017" ...
$ Time :Classes 'hms', 'difftime' atomic [1:990571] 41970 41969 41968 41967 41966 ...
.. ..- attr(*, "units")= chr "secs"
$ Bar# : chr "197953/197953" NA "197952/197953" NA ...
$ Bar Index : int 0 NA -1 NA NA -2 NA NA -3 NA ...
$ Tick Range: int 0 NA 0 NA NA 0 NA NA 0 NA ...
$ Open : num 33.9 NA 33.9 NA NA ...
$ High : num 33.9 NA 33.9 NA NA ...
$ Low : num 33.9 NA 33.9 NA NA ...
$ Close : num 33.9 NA 33.9 NA NA ...
$ Vol : int 100 NA 200 NA NA 100 NA NA 400 NA ...
$ MACDHist : num -59 NA -87 NA NA ...
$ MACD : num -450 NA -445 NA NA ...
$ MACDSig : num -391 NA -358 NA NA ...
$ ZScore1 : num NA NA NA NA NA NA NA NA NA NA ...
Hoping to use this function to speed things up in data cleaning.
Problem
After I run the function in the script editor, and then pass a data.frame to run it. But the function does not do anything and when I View(WFM), it's still the same old data. However, when I manually run the command:
WFM$Vol[is.na(WFM$Vol)] <- 0
Then it works.
Things I tried
I tried experimenting based on the two links I saw, being seemingly relevant:
Using WFM <- naToZero(WFM)
, produces a vector with a single value, 0.
Tried using WFM <- data.table(WFM)
and running the function... same thing.
I must be missing something basic.