-1

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

Sulz
  • 333
  • 1
  • 8
  • 1
    Your second chunk of code does not work. Actor is not defined. – Maël Aug 15 '22 at 10:11
  • I'm sorry. I skpit this coping form my Testscript, but just added it. Actor <- unique(c(A$Actor1, A$Actor2)) – Sulz Aug 15 '22 at 10:17
  • The Problem on the solution down for me is, that I have sometimes several observations in one day. In the new list, they shall be stored in one Dataframe. So there is a dataframe in the list for each day. – Sulz Aug 16 '22 at 11:49

1 Answers1

0

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
Maël
  • 45,206
  • 3
  • 29
  • 67