R 你可以在几年内找到共同的名字

R 你可以在几年内找到共同的名字,r,R,我有两列数据,第一列是1980年至2020年的年份,第二列包含每年的字符或名称。我感兴趣的是生成两列`表,其中一列显示特定名称的出现次数,另一列显示该名称复制的年份 知道怎么做吗? 提前感谢您的时间和帮助您的意思是像下面这样的聚合 aggregate(year ~ ., df, toString) 以致 > aggregate(year ~ ., df, toString) name year 1 A

我有两列数据,第一列是1980年至2020年的年份,第二列包含每年的字符或名称。我感兴趣的是生成两列`表,其中一列显示特定名称的出现次数,另一列显示该名称复制的年份

知道怎么做吗?

提前感谢您的时间和帮助

您的意思是像下面这样的
聚合

aggregate(year ~ ., df, toString)
以致

> aggregate(year ~ ., df, toString)
   name                         year
1     A             1983, 1990, 2012
2     B                   1984, 2007
3     C                         2014
4     D                         1981
5     E             2001, 2005, 2006
6     F                   2015, 2018
7     G                   1982, 1997
8     I                   1998, 2002
9     J 1993, 1996, 2008, 2016, 2017
10    K                         1986
11    L                         2010
12    N             1987, 1995, 2004
13    O             1999, 2011, 2019
14    R                         1988
15    S                         1989
16    T                   2013, 2020
17    U             1991, 1992, 2000
18    V                         1994
19    W                         1985
20    Y             1980, 2003, 2009
表格

> table(df)
      name
year   A B C D E F G I J K L N O R S T U V W Y
  1980 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
  1981 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  1982 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
  1983 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  1984 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  1985 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
  1986 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
  1987 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
  1988 0 0 0 0 0 0 0 0 0 0 0 0 0 1 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  2012 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  2013 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
  2014 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  2015 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  2016 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
  2017 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
  2018 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  2019 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
  2020 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
数据

set.seed(1)
df <- data.frame(
  year = 1980:2020,
  name = sample(LETTERS, 41, replace = TRUE)
)
set.seed(1)

df我非常喜欢@ThomasIsCoding解决方案,但这里有使用
dplyr
data.table
的解决方案

示例数据:

dat <- data.frame(
  year = sample(1990:1993, 10, replace=TRUE),
  name = sample(letters[1:4], 10, replace=TRUE))
数据表
解决方案:

library(data.table)

dt = data.table(dat)
dt[, .(.N, years=toString(sort(unique(year)))), by="name"]

#>    name N      years
#> 1:    b 2 1992, 1993
#> 2:    d 5 1992, 1993
#> 3:    c 2       1990
#> 4:    a 1       1993
library(data.table)

dt = data.table(dat)
dt[, .(.N, years=toString(sort(unique(year)))), by="name"]

#>    name N      years
#> 1:    b 2 1992, 1993
#> 2:    d 5 1992, 1993
#> 3:    c 2       1990
#> 4:    a 1       1993