簡體   English   中英

R中每個ID的互相關(CCF)/按ID

[英]Cross Correlation (CCF) in R for each ID / by ID

我對 R 很陌生。我的數據看起來(簡化)是這樣的:

ID <- c(1,1,1,1,2,2,3,3,3,3,4,4,4)
Affect <- c(0.8, 0.5, NA, 0.8, 0.2, 0.1, 0.7, 1.1, 0.9, 0.5, 0.3, NA, 0.9)
Paranoia <-  c(0.9, 0.6, 0.4, 0.2, 0.1, NA, 0.3, 0.1, 0.9, 1.5, 0.4, 0.1, 0.6)
df <- cbind(ID, Affect, Paranoia)

我想要計算 R 中的互相關以找出影響是否先於偏執或相反。 我怎樣才能做到這一點? 我嘗試了幾種方法,但從未成功。 先感謝您!

我們可以刪除all 'Affect' 或 'Paranoia' 作為NA的 'ID',然后用 0 ( replace_na ) replace剩余的 NA 並應用ccf

library(tseries)
library(dplyr)
library(tidyr)
out <- df %>%
         group_by(ID) %>%
         filter(!(all(is.na(Affect))|all(is.na(Paranoia)))) %>% 
         mutate_at(vars(Affect, Paranoia), replace_na, 0) %>% 
         summarise(ccfout = list(ccf(Affect, Paranoia)))


out$ccfout[[1]]
#
#Autocorrelations of series ‘X’, by lag

#    -3     -2     -1      0      1      2      3 
#-0.264 -0.078  0.575  0.229 -0.246 -0.521  0.305 
out$ccfout[[3]]

#Autocorrelations of series ‘X’, by lag

#    -3     -2     -1      0      1      2      3 
#-0.163  0.449  0.408 -0.735 -0.490  0.286  0.245 

或者使用group_split/map

library(purrr)
df %>%
    group_split(ID) %>% 
    map(~ .x %>% 
            mutate_at(vars(Affect, Paranoia), replace_na, 0) %>% 
        {ccf(.$Affect, .$Paranoia)})
#[[1]]

#Autocorrelations of series ‘X’, by lag

#    -3     -2     -1      0      1      2      3 
#-0.264 -0.078  0.575  0.229 -0.246 -0.521  0.305 

#[[2]]

#Autocorrelations of series ‘X’, by lag

#0 
#1 

#[[3]]

#Autocorrelations of series ‘X’, by lag

#    -3     -2     -1      0      1      2      3 
#-0.163  0.449  0.408 -0.735 -0.490  0.286  0.245 

#[[4]]

#Autocorrelations of series ‘X’, by lag

#    -1      0      1 
#-0.289  0.954 -0.636 

數據

df <- data.frame(ID, Affect, Paranoia)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM