2

I have a data frame with counts of each combination of a trait (true / false) for species A and B. Here's a smaller version of my data:

species <- c("A", "B") 
true <- c(3, 2) 
false <- c(1, 4) 
df <- data.frame(species, true, false)
df
  species true false
1       A    3     1
2       B    2     4

Is there any way to convert these summarized counts to one row for each registration, with first column for "Species" (A or B). Second column "Trait" (true or false):

Species    Trait
      A     true
      A     true
      A     true
      B     true
      B     true
      A    false
      B    false
      B    false
      B    false
      B    false

I don´t really know how to approach this, usually raw data is available and a summary table can easily be constructed from that, but this is the reverse way.

I´m thankful for every answer! :)

Henrik
  • 65,555
  • 14
  • 143
  • 159
Arsen
  • 21
  • 1
  • One possibility is `d <- melt(df, id.vars = "species")` ([Reshaping data.frame from wide to long format](https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format)); `d[rep(seq_len(nrow(d)), d$value), 1:2]` ([Replicate each row of data.frame and specify the number of replications for each row](https://stackoverflow.com/questions/2894775/replicate-each-row-of-data-frame-and-specify-the-number-of-replications-for-each)) – Henrik Feb 10 '18 at 20:12
  • 1
    Very helpful! That´s it, thanks Henrik. :) – Arsen Feb 10 '18 at 20:52

0 Answers0