dplyr数据透视表 [英] dplyr pivot table

查看:104
本文介绍了dplyr数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个具有递减值的数据透视表.

I want to obtain a pivot table with descending value.

library(dplyr)
library(tidyr)

h<-mtcars %>%
  group_by(cyl, gear) %>%
  tally() %>%
  spread(gear, n, fill = 0)
h<-h%>% add_rownames("index")

i<-mtcars %>%
  group_by(cyl, gear) %>%
  tally() %>%
  spread(cyl, n, fill = 0)

获取值的总和

j<-i%>%
  select(-1)%>%
  summarise_each(funs(sum))

k<-t(j)
k<- as.data.frame(k)
k<-tbl_df(k)
k<-k%>%add_rownames("index")

l<-left_join(h,k,by="index")
l<-l%>%
  select(-1)%>%
  arrange(desc(V1))

在dplyr中还有另一种方法吗?

Is there another way to do the same in dplyr?

推荐答案

我们按'cyl','gear'分组,获得频率计数(tally()),从'long'改成'wide'(使用<tidyr中的c1>),ungroup删除属性(以前,它不使用该属性),使用mutate创建"V1"作为每一行的sum(使用rowSums)并最后根据'V1'中的值arrange(order)行.

We group by 'cyl', 'gear', get the frequency count (tally()), reshape from 'long' to 'wide' (using spread from tidyr), ungroup to remove the attributes (previously, it used to work without this), use mutate to create 'V1' as the sum of each row (using rowSums) and finally arrange (order) the rows based on values in 'V1'.

library(dplyr)
library(tidyr)

mtcars %>%
   group_by(cyl, gear) %>% 
   tally() %>%
   spread(gear, n, fill=0) %>% 
   ungroup() %>%
   mutate(V1= rowSums(.[-1])) %>% 
   arrange(desc(V1))
#    cyl     3     4     5    V1
#  <dbl> <dbl> <dbl> <dbl> <dbl>
#1     8    12     0     2    14
#2     4     1     8     2    11
#3     6     2     4     1     7

这篇关于dplyr数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆