简体   繁体   English

将数据框元素转换为汇总表

[英]Transform Data Frame Elements Into a Summary Table

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! 谢谢!

If you don't care about the rownames of df you can use base R's stack : 如果你不关心rownamesdf可以使用基础R的stack

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

Or the tidyverse approach: tidyverse方法:

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
 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
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM