Count how many fall in each group in R [duplicate]

旧巷老猫 提交于 2021-01-29 14:32:33

问题


I have data something similar to this:

  User id    Ranking   Country 
    1           1         USA 
    2           3         AUS 
    3           1         USA 
    4           1         AUS 
    5           2         USA

and I would like to have the following results:

USA Ranking 1 = 2
USA Ranking 2 = 1
USA Ranking 3 = 0
AUS Ranking 1 = 1
AUS Ranking 2 = 0
AUS Ranking 3 = 1

How may I do this in R please?


回答1:


reshape2::melt(table(d$Country, factor(d$Ranking, 1:3)))
#  Var1 Var2 value
#1  AUS    1     1
#2  USA    1     2
#3  AUS    2     0
#4  USA    2     0
#5  AUS    3     1
#6  USA    3     0

DATA

structure(list(User.id = 1:4, Ranking = c(1L, 3L, 1L, 1L), Country = c("USA", 
"AUS", "USA", "AUS")), class = "data.frame", row.names = c(NA, 
-4L))



回答2:


A dplyr approach. Pretty easy to alter if wanted.

library(dplyr)
df = data.frame(
  UserID = seq(1:5),
  Ranking = c(1, 3, 1, 1, 2),
  Country = c("USA", "AUS", "USA", "AUS", "USA")
)


df_2 <- df %>% 
  group_by(Country, Ranking) %>% 
  summarise(Counts = n())

df_2

  Country Ranking Counts
1 AUS           1      1
2 AUS           3      1
3 USA           1      2
4 USA           2      1


来源:https://stackoverflow.com/questions/58066131/count-how-many-fall-in-each-group-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!