0

I have a data frame and I would like to create a table of all cell values, along with their row and column names. For example,

a <- c(1:4)
df <- matrix(a, nrow = 2, ncol = 2, byrow = T)
rownames(df) <- c("Paul", "Matt")
colnames(df) <- c("Beach", "Hike")
df <- as.data.frame(df)
df

I would like the output to be a data frame with the following columns:

Paul | 1 | Beach
Paul | 2 | Hike
Matt | 3 | Beach
Matt | 4 | Hike

I need to sort the numeric value for all combinations of rows and colums for a very large data set so if anyone could help me out that'd awesome :)

Thanks!

DJC
  • 1,491
  • 6
  • 19
  • Also : `melt(df)` https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format could be helpful. – Ronak Shah Feb 22 '18 at 05:09

3 Answers3

1

If you don't care about the rownames of df you can use base R's stack:

stack(df);
#  values   ind
#1      1 Beach
#2      3 Beach
#3      2  Hike
#4      4  Hike

Or the tidyverse approach:

require(tidyverse);
df %>% 
    gather(key, values, 1:2) %>% 
    mutate(id = rep(rownames(df), ncol(df))) %>% 
    arrange(desc(id));
#    key values   id
#1 Beach      1 Paul
#2  Hike      2 Paul
#3 Beach      3 Matt
#4  Hike      4 Matt
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
0
 library(tidyverse)
  df %>% 
  rownames_to_column(var="name") %>% 
  gather(key,value,-name) %>% 
  arrange(value)

  name   key value
1 Paul Beach     1
2 Paul  Hike     2
3 Matt Beach     3
4 Matt  Hike     4
vsb
  • 428
  • 6
  • 15
0
res_df = data.frame()
for(x in rownames(df)){
   for(y in colnames(df)){
      res_df = rbind(res_df, as.data.frame(t(c(person=x, count=df[x,y], activity=y))))
   }
}


  person count activity
1   Paul     1    Beach
2   Paul     2     Hike
3   Matt     3    Beach
4   Matt     4     Hike
Devaraj Phukan
  • 196
  • 1
  • 9