问题
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)
To obtain the sum of the values
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))
Is there another way to do the same in dplyr?
回答1:
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
来源:https://stackoverflow.com/questions/29720473/dplyr-pivot-table