简体   繁体   中英

How to subset dataframe by last characters of a string in R

R-user,

I have this dataframe:

head(Niger_Meteo_98.11)
  X.ID_punto    MM.GG.AA T2m_max  
1          1    01/01/98 303.235 
2          2    01/01/99 303.356 
3          3    01/01/00 303.477 
4          4    01/01/01 303.604 
5          5    01/01/02 303.759 
6          6    01/01/03 303.915 

and I need to get only values from year 2002. So, I should select, on column MM.GG.AA , those rows that end with " /02 ". I didn't find anything online...any hints? Thanks!

Use standard subsetting with grep , like this:

x <- read.table(text="  X.ID_punto    MM.GG.AA T2m_max  
1          1    01/01/98 303.235 
2          2    01/01/99 303.356 
3          3    01/01/00 303.477 
4          4    01/01/01 303.604 
5          5    01/01/02 303.759 
6          6    01/01/03 303.915", header=TRUE)

x[grep("/02$", x$MM.GG.AA), ]

  X.ID_punto MM.GG.AA T2m_max
5          5 01/01/02 303.759

The grep regular expression /02$ searches for string that end in /02 , since the $ indicates the end of the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM