Marek
Marek

Reputation: 245

Extract rows based on last value of row R

I'm very new to R, so just bear with me.

I have a dataframe df:

ID,NUM,REV,HRY
1221838,2556200,17396.979,L
9677461,5562000,0.000,L
9636801,5562215,0.000,L
9713221,5562222,25739.479,L

i want to extract those rows, whose NUM value ends with 0. Similarly for 1,2,..9.

In this case output for those records whose NUM value ends with 0 will be df_out,

ID,NUM,REV,HRY
1221838,2556200,17396.979,L
9677461,5562000,0.000,L

Is there any way to do this in R? Thanks in advance.

Upvotes: 0

Views: 60

Answers (2)

Prradep
Prradep

Reputation: 5696

We can use dplyr's filter() together with grepl() to extract rows with NUM having values ending with 0.

df_out <- df %>% filter(grepl('0$',NUM))
df_out
#        ID     NUM      REV HRY
# 1 1221838 2556200 17396.98   L
# 2 9677461 5562000     0.00   L

Upvotes: 1

akrun
akrun

Reputation: 887048

We can use substring to get the last digit to be used as logical condition in subset

subset(df1, substring(NUM, nchar(NUM))==0)
#        ID     NUM      REV HRY
#1 1221838 2556200 17396.98   L
#2 9677461 5562000     0.00   L

Based on @lmo's comments and the update in the OP's post, we can create multiple datasets in a list with split

lst <- split(df1, substring(df1$NUM, nchar(df1$NUM)))

Upvotes: 1

Related Questions