-2

I have a data frame with names for row identity and dates as column identity.

df <- data.frame(`20171007` = c(8, 4),
                 `20171014` = c(9, 7),
                 row.names = c("Kohl", "Travis"))

What I want is a data structure with three columns, where the identity is actually data.

Date (get from column identity)
Name (get from row identity)
Value (get from df[r,c])

In this particular case I would end up with 4 rows, one for each value. How do I go about flattening my df into that structure?

andyczerwonka
  • 4,230
  • 5
  • 34
  • 57

3 Answers3

3

You can do something like this with tidyverse:

library(tidyverse)

df %>%
  rownames_to_column(var = "Name") %>%      # tibble
  gather(Date, Value, -Name) %>%            # tidyr
  mutate(Date = as.Date(Date, "X%Y%m%d"))   # dplyr

Result:

    Name       Date Value
1   Kohl 2017-10-07     8
2 Travis 2017-10-07     4
3   Kohl 2017-10-14     9
4 Travis 2017-10-14     7

Data:

df = data.frame(`20171007` = c(8, 4),
                `20171014` = c(9, 7),
                row.names = c("Kohl", "Travis"))
acylam
  • 18,231
  • 5
  • 36
  • 45
1

The simple one-liner is to transpose the df and then melt (from reshape2)

melt(t(df), value.name = "Value", varnames = c("Date", "Name"))
andyczerwonka
  • 4,230
  • 5
  • 34
  • 57
0

The simplest thing to do is use something similar to below. One note of caution, it is not generally good practice to have a numeric as a column name. This will lead to compatibility issues with other functions.

df = data.frame(`20171007` = c(8,4), 
            `20171014` = c(9, 7))
row.names(df) = c('Kohl', 'Travis')

Create column with row names

df$names <- row.names(df)

Use the package tidyr to reshape data

EDIT - @useR

df %>% 
  gather(date, value, -names)
jacobsg
  • 121
  • 6
  • This doesn't give the desired result, since your `names` is also gathered. You need to exclude `name` from `gather` like `df %>% gather(date, value, -name)` from my answer – acylam Oct 16 '17 at 21:34
  • Right you are. Thanks for the information. I like your much better anyways (without the gaff). – jacobsg Oct 17 '17 at 14:53