Lingyu Kong Lingyu Kong - 4 months ago 31
R Question

How to cast value as the first column from dataframe in R?

I am working on a DF like:

firm <- c("A","A","B","B")
CEO <- c("John",NA,"Sam",NA)
Manager <- c("Alger","Tabor","Tad","Eartha")
df <- data.frame(firm,CEO,Manager)

firm CEO Manager
1 A John Alger
2 A <NA> Tabor
3 B Sam Tad
4 B <NA> Eartha

I want use dcast to reshape the data by their names like following:

name firm position
1 John A CEO
2 Alger A Manager
3 Tabor A Manager
4 Sam B CEO
5 Tad B Manager
6 Eartha B Manager

Is it possible to reshape data like this?


We can use the hadleyverse gather from tidyr

gather(df,  position, name,  -firm, na.rm = TRUE)
#   firm position   name
#1    A      CEO   John
#3    B      CEO    Sam
#5    A  Manager  Alger
#6    A  Manager  Tabor
#7    B  Manager    Tad
#8    B  Manager Eartha