R如何根据列的第一个字符删除数据框中的行 [英] R how to remove rows in a data frame based on the first character of a column

查看:314
本文介绍了R如何根据列的第一个字符删除数据框中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大数据框,并且我想根据列的第一个字符是字母或数字从其中删除某些行。我的数据框示例如下所示:

I have a big data frame and I want to remove certain rows from it based on first char of a column being a letter or a number. Sample of my data frame looks like a below:

y<-c('34TA912','JENAR','TEST','34CC515')
z<-('23.12.2015','24.12.2015','24.12.2015','25.12.2015')
abc<-data.frame(y,z)

基于上述示例。由于第二行和第三行的y列中的值以字母而不是数字开头,因此我想删除第二行和第三行。 Y列中写入的字符可以是任何字符,因此我可以过滤的唯一方法是在不使用任何预定义值的情况下检查第一个字符。如果我将grep与字符一起使用,由于其他行也包含字母,因此也可以将其删除。您可以提供帮助吗?

Based on the sample above. I would like to remove second and third rows due to the value in y column in second row and third row starting with a letter instead of a number. Characters written in Y column could be anything, so only way I could filter is checking the first character without using any predefined value. If I use grep with a character, since other rows also contain letter, I could remove them aswell. Can you assist?

推荐答案

我们可以使用 grep 。正则表达式 ^ 指示字符串的开头。我们使用 grep [0-9] ) >。输出将是数字索引,我们将其用于子集 abc的行。

We can use grep. The regex ^ indicates the beginning of the string. We match numeric element ([0-9]) at the beginning of the string in the 'y' column using grep. The output will be numeric index, which we use to subset the rows of the 'abc'.

 abc[grep('^[0-9]', abc$y),]
 #        y          z
 #1 34TA912 23.12.2015
 #4 34CC515 25.12.2015

这篇关于R如何根据列的第一个字符删除数据框中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆