0

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?

1 Answers1

1

We can use the hadleyverse gather from tidyr

library(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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • thanks for the code. but I got **Warning message: attributes are not identical across measure variables; they will be dropped **. What does this mean? What has been dropped? – Lingyu Kong Aug 22 '16 at 14:30
  • 1
    @LingyuKong It is because the columns were `factor` class (by default, the `data.frame(.., stringsAsFactors=TRUE)`, if you have used `data.frame(..., stringsAsFactors=FALSE)`, it would have been `character` class for the nonnumeric columns (here all are non-numeric BTW), So, what happens is that the `levels` of the `factor` are different, and when we `melt/gather` it the differnt levels get united and a spark happens due to the difference in levels. This triggers the warning. But, it is a friendly warning and nothing to worry about. – akrun Aug 22 '16 at 14:33
  • I am wondering, If it is possible to use melt() to get this done, as gather() analogous to the melt function from reshape2. – Lingyu Kong Aug 23 '16 at 00:47
  • 1
    @LingyuKong You can use `melt` as well. `melt(df, id.var = "firm", na.rm = TRUE)` – akrun Aug 23 '16 at 03:06