0

I have a dataframe which consist of 23 variables. I want to calculate the growth rate by lag 1 of the first 22 variables. I tried to make a list mylist of all 22 columns and then use lapply function but it is not working. The dataset is called data_nse

  temp4 <- lapply(mylist,function(x){ 
  data_nse$x <- (x-lag(x,1))/lag(x,1)  
 x})

I get the following error

>  Error in attr(x, "tsp") <- c(1, NROW(x), 1) :    invalid time series
> parameters specified

What is the correct and efficient way to do this? I am new to R.

Thanks in advance!

Sankalp Mathur
  • 119
  • 1
  • 5
  • You are probably using base R `lag` when you want dplyr's `lag`. Call `library(dplyr)` before you run this code and see if it helps. See `?lag` and `?dplyr::lag` for more info. –  May 09 '18 at 10:16
  • The other problem is that you are first using `x` as a name of a variable, but trying to assign to `data_nse$x`. That doesn't work: it will assign to a new column literally named "x". Instead, assign to `data_nse[[x]]`. –  May 09 '18 at 10:18
  • And at the same time, you are using `x` as an actual value. Hmm, this is a mess. Please create a proper [mcve] and we'll be able to understand what you are doing wrong. –  May 09 '18 at 10:19
  • @dash2 thanks for response. I did call the library(dplyr) before running the code and I tried assigning data_nse[[x]]. I am getting this: – Sankalp Mathur May 09 '18 at 10:27
  • Error in `[[<-`(`*tmp*`, i, value = value) : no such index at level 1 – Sankalp Mathur May 09 '18 at 10:27
  • Don't thank me... just provide a [mcve]. –  May 09 '18 at 10:31

0 Answers0