0
votes

I have some event data that I want to gather in one column. At the moment the data include columns for events and other columns that contain the outcome of certain events. I want to include the outcomes as events in the data and also preserve the order. The data look like df in the example below and I want to transform them so that they look like the desired df.

a <- c("event1","event2","event3","event4")
b <- c("outcome1",'','','')
c <- c('','',"outcome3",'')

df <- data.frame(a,b,c)

d <- c("event1","outcome1","event2","event3","outcome3","event4")
desired <- data.frame(d)
1

1 Answers

1
votes

We can convert the data to matrix by transposing, collapse it into one vector and remove the empty values

vals <- c(t(df))
data.frame(d = vals[vals!= ""])

#         d
#1   event1
#2 outcome1
#3   event2
#4   event3
#5 outcome3
#6   event4

Using tidyverse

library(dplyr)
tidyr::pivot_longer(df, cols = names(df)) %>%
   filter(value != "") %>%
   select(value)