Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...