Home > Back-end >  creating an list of occurence dataframes (two sided matrix) in R
creating an list of occurence dataframes (two sided matrix) in R

Time:08-15

My original Dataframe looks like

A <- data.frame(Actor1 = c("A1", "B2", "C3", "D4"),
           Actor2 = c("A1", "C4", "F2", "B2"),
           Dates = as.Date(c('1999/01/01', "1999/02/05", "1999/05/06", "2000/03/06")),
           Case = c(4, 6, 8, 10))
Actor <- unique(c(A$Actor1,  A$Actor2))

I wish to transform this actor-event-based Dataframe to convert it to an occurence list of dataframes, where every dataframe representing a extra day, and the row and column names of each Dataframe are the actorsname of the original Dataframe. If they interact in one day, it should be a 1 on the dataframe of this day.

At the end it should be look like but for all days given in a certain timespan.:

Jan_01_99 <- data.frame(matrix(ncol = 6, nrow = 6))
colnames(Jan_01_99) <- Actor
rownames(Jan_01_99) <- Actor
Jan_01_99[1,1] <- 1
Jan_02_99 <- data.frame(matrix(ncol = 6, nrow = 6))
colnames(Jan_02_99) <- Actor
rownames(Jan_02_99) <- Actor

Feb_05_99 <- data.frame(matrix(ncol = 6, nrow = 6))
colnames(Feb_05_99) <- Actor
rownames(Feb_05_99) <- Actor
Feb_05_99[2,5] <- 1
complete_List <- list(Jan_01_99, Jan_02_99, Feb_05_99)

Anyone have an approach how to do this? Thanks

CodePudding user response:

Here's a way:

library(tidyverse)
A %>% 
  mutate(across(c(Actor1, Actor2), factor, levels = Actor)) %>% 
  split(seq(nrow(.))) %>% 
  map(~ table(.[1:2]))

output

$`1`
      Actor2
Actor1 A1 B2 C3 D4 C4 F2
    A1  1  0  0  0  0  0
    B2  0  0  0  0  0  0
    C3  0  0  0  0  0  0
    D4  0  0  0  0  0  0
    C4  0  0  0  0  0  0
    F2  0  0  0  0  0  0

$`2`
      Actor2
Actor1 A1 B2 C3 D4 C4 F2
    A1  0  0  0  0  0  0
    B2  0  0  0  0  1  0
    C3  0  0  0  0  0  0
    D4  0  0  0  0  0  0
    C4  0  0  0  0  0  0
    F2  0  0  0  0  0  0

$`3`
      Actor2
Actor1 A1 B2 C3 D4 C4 F2
    A1  0  0  0  0  0  0
    B2  0  0  0  0  0  0
    C3  0  0  0  0  0  1
    D4  0  0  0  0  0  0
    C4  0  0  0  0  0  0
    F2  0  0  0  0  0  0

$`4`
      Actor2
Actor1 A1 B2 C3 D4 C4 F2
    A1  0  0  0  0  0  0
    B2  0  0  0  0  0  0
    C3  0  0  0  0  0  0
    D4  0  1  0  0  0  0
    C4  0  0  0  0  0  0
    F2  0  0  0  0  0  0
  • Related