C_Mu
C_Mu

Reputation: 325

R function with lapply not working

I am trying to use function to do a difference calculation. If I dont use function and run code line by line. It works perfectly. However if I use function to run the same thing, it doesnt work. I could not figure out why and any idea from you is welcome!

date=c('2018-01-01', '2018-02-01', '2018-03-01')
a=c(1,3,2)
b=c(89,56,47)
c=c(1872,7222,2930)
x=data.frame(date,a,b,c)

f1 = function(table_df1, table_df2) {

  table_df1 = as.data.table(table_df1)
  cols = colnames(table_df1)
  cols = cols[-1]
  table_df2 = table_df1[,(paste0(cols, "_pctChange")) := lapply(.SD, function(col){ 
    (col-shift(col,1,type = "lag"))/shift(col,1,type = "lag")
  }), .SDcols=cols]

 rm(cols)

}

f1(x,x2)

Upvotes: 0

Views: 45

Answers (1)

GordonShumway
GordonShumway

Reputation: 2056

You only need one input to your function as it only manipulates table_df1. Also you don't need the rm(cols) as cols only exists in the function environment and so will not exist once the function call has terminated.

f1 = function(table_df1) {
  table_df1 = as.data.table(table_df1)
  cols = colnames(table_df1)
  cols = cols[-1]
  table_df2 = table_df1[,(paste0(cols, "_pctChange")) := lapply(.SD, function(col){ 
    (col-shift(col,1,type = "lag"))/shift(col,1,type = "lag")
  }), .SDcols=cols]     
}

x2 <- f1(x)
print(x2)
         date a  b    c a_pctChange b_pctChange c_pctChange
1: 2018-01-01 1 89 1872          NA          NA          NA
2: 2018-02-01 3 56 7222   2.0000000  -0.3707865   2.8579060
3: 2018-03-01 2 47 2930  -0.3333333  -0.1607143  -0.5942952

Upvotes: 1

Related Questions