Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

dataframe - R: how to count repeated character observations for a variable in a data frame

I have a data frame like this:

> head(Sp)
# A tibble: 6 x 4
  fechacolecta aniocolecta especievalida           fecha     
  <chr>              <dbl> <chr>                   <date>    
1 1865-07-17          1865 Geranium carolinianum   1865-07-17
2 1865-07-17          1865 Paspalum distichum      1865-07-17
3 1890-07-27          1890 Sporobolus pyramidatus  1890-07-27
4 1893-05-02          1893 Schiedeella durangensis 1893-05-02
5 1893-05-07          1893 Mesadenus polyanthus    1893-05-07
6 1893-05-07          1893 Mesadenus polyanthus    1893-05-07

And what I'm loooking for is to know how many times for example "Geranium carolinianum" is present in the data frame, if there was a way that the result could also maintain tha dates in which Geranium carolinianum is present it would be nice, also, I don't know the valuables the especievalida column might take. The unique() function only returns which species are present, but not how many times, and it only returns that variable, doesn′t include the date. Thank you for your attention.

question from:https://stackoverflow.com/questions/65908112/r-how-to-count-repeated-character-observations-for-a-variable-in-a-data-frame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
library(tidyverse)

Sp %>%
  # filters for the species
  filter(especievalida == "Geranium carolinianum") %>%
  # creates a column for count
  mutate(count = n())

Data

Sp <- read.table(text = "
fechacolecta aniocolecta especievalida fecha
1865-07-17 1865 'Geranium carolinianum' 1865-07-17
1865-07-17 1865 'Paspalum distichum' 1865-07-17
1890-07-27 1890 'Sporobolus pyramidatus' 1890-07-27
1893-05-02 1893 'Schiedeella durangensis' 1893-05-02
1893-05-07 1893 'Mesadenus polyanthus' 1893-05-07
1893-05-07 1893 'Mesadenus polyanthus' 1893-05-07", 
header = T)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...