分析R中的data.frame

时间:2018-04-06 18:20:36

标签: r dataframe

我有一个像这样的data.frame:

# Scientific.Name             Year

# Sympetrum                   2012
# Celithemis eponina          2012
# Celithemis elisa            2012
# Celithemis elisa            2012
# Cordulegaster maculata      2011
# Calopteryx maculata         2011
# Celithemis elisa            2013
# Celithemis elisa            2013

我想制作一个如下所示的data.frame:

                                Year
# Scientific.Name               2011     2012     2013
# Sympetrum                         0        1        0
# Celithemis eponina                0        1        0
# Celithemis elisa                  0        2        2
# Cordulegaster maculata            1        0        0
# Calopteryx maculata               1        0        0

我希望有一列独特的物种名称,其余的列是独特的年份。我想计算每年收集一个独特物种的次数,并将其作为data.frame返回。我想要转换的实际data.frame几乎是3,000个观测值,但我只需要82行(82种)。

1 个答案:

答案 0 :(得分:2)

table()函数可以解决问题

df <- data.frame(Scientific.Name = c("Sympetrum", "Celithemis eponina", "Celithemis elisa", "Celithemis elisa",
                                     "Cordulegaster maculata", "Calopteryx maculata", "Celithemis elisa", "Celithemis elisa"),
                 Year = c(2012, 2012, 2012, 2012, 2011, 2011, 2013, 2013))
table(df)


                        Year
Scientific.Name          2011 2012 2013
  Calopteryx maculata       1    0    0
  Celithemis elisa          0    2    2
  Celithemis eponina        0    1    0
  Cordulegaster maculata    1    0    0
  Sympetrum                 0    1    0