[R] extracting numeric values returned when using the by function to run the acf function

Sarah Goslee @@r@h@go@|ee @end|ng |rom gm@||@com
Tue May 10 19:44:32 CEST 2022


Hi,

You can either write a small function that returns just the values you
want, or use a convenience function within by, as in:

> by(RecallSmall[1:4,"value"],RecallSmall[1:4,"ID"], FUN=function(x){acf(x, na.action=na.pass,plot=FALSE)$acf})
RecallSmall[1:4, "ID"]: 1
, , 1

      [,1]
[1,]  1.00
[2,]  0.15
[3,] -0.50
[4,] -0.15

But I suspect that you would get something more like what you want by
splitting the data on ID, and then using sapply:

> RecallSmall <- data.frame(ID=c(1,1,1,1,2,2,2,2), value=c(6,5,3,4,6,5,3,4))
> result <- split(RecallSmall[["value"]], RecallSmall[["ID"]])
> result <- sapply(result, FUN=function(x){acf(x, na.action=na.pass,plot=FALSE)$acf})
> result
         1     2
[1,]  1.00  1.00
[2,]  0.15  0.15
[3,] -0.50 -0.50
[4,] -0.15 -0.15


Sarah

On Tue, May 10, 2022 at 1:29 PM Sorkin, John <jsorkin using som.umaryland.edu> wrote:
>
> I am using the by function to run the acf function. Each run of the by function returns more information than I want. All I want is the four values that acf returns, which using the data below would be
> 1.00  0.15   -0.50  -0.15
> How  can I isolate these four values from the output returned by the by function.
>
> Sample code:
>
> RecallSmall <- data.frame(ID=c(1,1,1,1),value=c(6,5,3,4))
> cat("Here are the data\n")
> RecallSmall
> cat("All I want is autocorrerlations, e.g. 1.00  0.15 -0.50 -0.15 \n ")
> # attempting to subset does not work at all
> by(RecallSmall[1:4,"value"],RecallSmall[1:4,"ID"],acf,na.action=na.pass,plot=FALSE)$acf
> # this gives me more than I want, not just the numeric results.
> by(RecallSmall[1:4,"value"],RecallSmall[1:4,"ID"],acf,na.action=na.pass,plot=FALSE)
>
> # For your reference, this is what the acf function returns
> acf(RecallSmall[1:4,"value"],na.action=na.pass,plot=FALSE)
> # For your reference, this is what the acf function returns when the output is subset
> acf(RecallSmall[1:4,"value"],na.action=na.pass,plot=FALSE)Thank you, John
>
> Thank you,
> John
>
>
>
>
>
>
>
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



-- 
Sarah Goslee (she/her)
http://www.numberwright.com



More information about the R-help mailing list