R根据团队名称计算团队成员的数量

R count number of Team members based on Team name

我有一个 df,其中每一行代表一个人,每一列代表这些人的特征。其中一列是 TeamName,这是个人所属团队的名称。多个人属于一个团队。

我想要 R 中的一个函数,它可以创建一个新列,其中包含每个团队的团队成员数量。

因此,例如我有:

df
Name    Surname     TeamName
John     Smith      Champions
Mary     Osborne    Socceroos
Mark     Johnson    Champions
Rory     Bradon     Champions
Jane     Bryant     Socceroos
Bruce    Harper     

我想要

df1
Name    Surname     TeamName    TeamNo
John     Smith      Champions     3
Mary     Osborne    Socceroos     2
Mark     Johnson    Champions     3
Rory     Bradon     Champions     3  
Jane     Bryant     Socceroos     2
Bruce    Harper                   0

所以你可以看到计数也包括那个人,如果某人(例如 Bruce Harper)没有团队名称,那么他得到 0。

我该怎么做?谢谢!

这是一个基于使用 data.table 的解决方案,这可能对您的需要来说太多了,但这里是:

library(data.table)
dt=data.table(df)
# First, let's convert the factors of TeamName, to characters
dt[,TeamName:=as.character(TeamName)]
# Now, let find all the team numbers
dt[,TeamNo:=.N, by='TeamName']
# Let's exclude the special cases
dt[is.na(TeamName),TeamNo:=NA]
dt[TeamName=="",TeamNo:=NA]

这显然不是最好的解决方案,但我希望这对您有所帮助

如果您需要根据 'TeamName' 列了解前两列中的 unique 成员数,一个选项是 n_distinct from dplyr

 library(dplyr)
 library(tidyr)
 df %>%
     unite(Var, Name, Surname) %>% #paste the columns together
      group_by(TeamName) %>% #group by TeamName
      mutate(TeamNo= n_distinct(Var)) %>% #create the TeamNo column
      separate(Var, into=c('Name', 'Surname')) #split the 'Var' column

或者如果它只是每个 'TeamName' 的行数,我们可以按 'TeamName' 分组,用 n() 得到每组的行数,创建 'TeamNo' 列 mutate 基于 n(),如果需要,可以使用 ifelse 条件为 'TeamName' 提供 '' 或 [=21] 的 NA =].

df %>%
   group_by(TeamName) %>%
   mutate(TeamNo = ifelse(is.na(TeamName)|TeamName=='', NA_integer_, n())) 
#   Name Surname  TeamName TeamNo
#1  John   Smith Champions      3
#2  Mary Osborne Socceroos      2
#3  Mark Johnson Champions      3
#4  Rory  Bradon Champions      3
#5  Jane  Bryant Socceroos      2
#6 Bruce  Harper                NA

或者您可以使用 base R 中的 ave。假设如果有''NA,我会先把''转换成NA,然后用ave得到length =40=] 按该列分组。对于“NA”值,它将给出 NA。例如。

  v1 <- c(df$TeamName, NA)# appending an NA with the example to show the case
  is.na(v1) <- v1=='' #convert the `'' to `NA`
  as.numeric(ave(v1, v1, FUN=length))
  #[1]  3  2  3  3  2 NA NA

使用sqldf:

library(sqldf)
sqldf("SELECT Name, Surname, TeamName, n
      FROM df 
      LEFT JOIN
      (SELECT TeamName, COUNT(Name) AS n 
      FROM df 
      WHERE NOT TeamName IS '' GROUP BY TeamName)
      USING (TeamName)")

输出:

   Name Surname  TeamName  n
1  John   Smith Champions  3
2  Mary Osborne Socceroos  2
3  Mark Johnson Champions  3
4  Rory  Bradon Champions  3
5  Jane  Bryant Socceroos  2
6 Bruce  Harper           NA