yanga yanga -4 years ago 142
R Question

How to Convert a Data Frame to a List for Clickstream Analysis

I am a novice R user and new to the forum.
I have a data frame that I need to convert so that each row is a character vector.
I want to remove the 0's from the data frame so that each row can have varying lengths. So in essence each row is a separate character vector in a list.
Where I am at is the following:

mydf<-matrix(sample(0:1,12*5, replace = T),ncol =4)
colnames(mydf)<-letters[1:ncol(mydf)]
swapcol <-which(mydf == 1, arr.ind = T)
mydf[swapcol]<-colnames(mydf)[swapcol[,2]]
mydf


The code produces a data frame in which the column labels are values. I need the following output:

Desired List Result

the format appears to be what I need in order to read in data to the package clickstream.
Thanks

Answer Source

Try this solution:

library(tidyverse)

s <- sample(x = 0:1, size = 15 * 4, replace = TRUE)

mx <- matrix(data = s, nrow = 15, ncol = 4, byrow = TRUE, 
dimnames = list(c(paste("User", 1:15, sep = " ")), c("V1", "V2", "V3", "V4")))

df2 <- mx %>% as.data.frame() %>% rownames_to_column() %>% as_tibble() 
%>% mutate(
  V1 = ifelse(test = V1 == 1, yes = "a", no = NA), 
  V2 = ifelse(test = V2 == 1, yes = "b", no = NA), 
  V3 = ifelse(test = V3 == 1, yes = "c", no = NA), 
  V4 = ifelse(test = V4 == 1, yes = "d", no = NA))

mx2 <- t(apply(X = df2, MARGIN = 1, FUN = function(x{return(c(x[!is.na(x)], 
x[is.na(x)]))}))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download