【问题标题】:Create data of frequency of interactions between variables using R使用 R 创建变量之间交互频率的数据
【发布时间】:2019-04-02 21:47:57
【问题描述】:

我想使用 R 计算二元交互频率表。我需要计算每个月动物之间的交互次数,然后计算总计。数据示例如下:

#Create sample data
B1 <-data.frame(Animal = c("A","B","C","D","E","A","B","C","D","E","A","B","C","D","E","A","B","C","D","E","A","B","C","D","E"), Location = c(1,1,2,1,3,4,2,1,1,3,3,4,3,1,1,4,2,2,2,1,1,3,4,3,2), Month = c("Jan","Jan","Jan","Jan","Jan","Feb","Feb","Feb","Feb","Feb","Mar","Mar","Mar","Mar","Mar","Apr","Apr","Apr","Apr","Apr","May","May","May","May","May"))

使用这些数据,我希望能够成对展示每月出现在某个地点的动物 例如,使用位置的配对的预期结果应该类似于 1 月份:

#Sample extract for January
B1Jan <- data.frame(Animal1= c("A", "A","B") ,Animal2=c("B","D","D") )
B1Jan
  Animal1 Animal2
1       A       B
2       A       D
3       B       D

在每个月提取之后,我希望能够计算每对之间的交互总数,例如可能 A-D 交互总共发生了 3 次。

请问最好的方法是什么?

【问题讨论】:

    标签: r dplyr data.table tidyverse zoo


    【解决方案1】:

    使用data.table,您可能可以执行以下操作:

    library(data.table)
    
    #convert into data.table
    setDT(B1)
    
    #create interaction between animals in the same location & month    
    ans <- B1[, if (.N > 1L) transpose(combn(unique(Animal), 2L, simplify=FALSE)), 
        by=.(Location, Month)]
    
    #change column names to desired column names
    setnames(ans, paste0("V", 1L:2L), paste0("Animal", 1L:2L))
    
    #sort animals so that A, B and B, A are the same
    ans[, paste0("Animal", 1L:2L) := .(pmin(Animal1, Animal2), pmax(Animal1, Animal2))]
    
    #count the number of interactions as requested
    ans[, .(NumInteract=.N), by=c(paste0("Animal", 1L:2L))]
    

    输出:

       Animal1 Animal2 NumInteract
    1:       A       B           1
    2:       A       D           1
    3:       B       D           3
    4:       C       D           2
    5:       A       C           1
    6:       D       E           1
    7:       B       C           1
    

    【讨论】:

    • 谢谢@chinsoon12。这行得通。我还尝试使用三个“by”列。
    • 还有一件事;目前,在我的实际数据集中,我将 A 到 C 和 C 到 A 表示为两种不同的交互。请问有没有办法添加一条线以确保它将 A 到 C 或 C 到 A 计为同一对?
    • @JokeO。我添加了一条线来按每行对动物进行排序。 hth
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 2021-09-09
    • 2016-11-26
    • 1970-01-01
    相关资源
    最近更新 更多