根据行R的最后一个值提取行

时间:2022-03-15 20:06:30

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

我对R很新,所以请耐心等待。

I have a dataframe df:

我有一个数据帧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.

我想提取那些NUM值以0结尾的行。类似于1,2,.. 9。

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

在这种情况下,NUM值以0结尾的记录的输出将为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.

在R中有没有办法做到这一点?提前致谢。

2 个解决方案

#1


1  

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

我们可以使用substring来获取最后一个数字作为子集中的逻辑条件

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

根据@ lmo的评论和OP帖子中的更新,我们可以在列表中创建多个数据集并进行拆分

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

#2


1  

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

我们可以使用dplyr的filter()和grepl()来提取NUM,其值为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

#1


1  

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

我们可以使用substring来获取最后一个数字作为子集中的逻辑条件

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

根据@ lmo的评论和OP帖子中的更新,我们可以在列表中创建多个数据集并进行拆分

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

#2


1  

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

我们可以使用dplyr的filter()和grepl()来提取NUM,其值为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

相关文章