-2

Basically, what I want to do is run the function ndiffs on each column of a dataframe and then store these results in another dataframe so for example if I have a dataframe of 5 columns I would have as a result a dataframe with 5 columns and only 1 row. In each column of the results dataframe their is the result of the ndiffs function applied to the same column index on the original dataframe.

I was able to do this by looping through the columns using the code below:

df is the original dataframe and df2 is the result

dataframe
df2=cbind(" ",ndiffs(as.numeric(unlist(df[2])), alpha =0.05, test ="adf", max.d = 3))
for (i in 3:ncol(df)){df2=cbind(df2,ndiffs(as.numeric(unlist(df[i])),alpha =0.05, test ="adf", max.d = 3))}

Is there a cleaner way to do this or not ?

J.Doe
  • 166
  • 1
  • 9

2 Answers2

1

Without a complete reproducible example this is an estimate of what you want:

df_2 <- apply(df, 2, ndiffs(as.numeric(x), alpha =0.05, test ="adf", max.d = 3)

Which basically says save in df_2, the results of ndiffs(with your criteria) applied across columns (2 is the designation for apply to columns and 1 for rows)

If your matrix/data frame is pure, and you coded ndiffs right above, this should provide you what you seek without a loop and if the data is big it is much faster than a loop.

sconfluentus
  • 4,693
  • 1
  • 21
  • 40
-2
df_2 <- as.data.frame(t(setNames(data.frame(apply(df[,2:ncol(df)], 2, function(x) ndiffs(as.numeric(unlist(x)), alpha =0.05, test ="adf", max.d = 3))), " ")))
J.Doe
  • 166
  • 1
  • 9
  • 1
    If you are answering your own question, it's best to explain what your solution is and why it's an appropriate solution. Bare code without the explanation may not help others who have similar problems in the future. – Jeff Zeitlin Jan 10 '18 at 16:26