删除行而不返回不正确的结果

时间:2015-11-07 05:49:36

标签: r

我正在尝试根据一列删除其中没有数字的行。我认为这将是一个简单的过程,但我遇到了一个问题:

> head(cond$Q26)
[1] "1"                                "1"                                ""                                
[4] "Q26"                              "Click to write the question text" "1"                               
> cond<-cond[is.numeric(cond$Q26)]
> head(cond)
data frame with 0 columns and 6 rows

任何人都有关于我如何解决这个问题的建议?我没有错误信息就卡住了。

1 个答案:

答案 0 :(得分:0)

我们可以使用grep来匹配从字符串的开头(\\D*)到结尾(^)的零个或多个非数字字符($)并使用它来对'cond'的行进行子集化。

cond1 <- cond[grepl('^\\D*$', cond$Q26),, drop=FALSE]
cond1
#                             Q26
#3                                 
#5 Click to write the question text

如果我们只需要在'Q26'上获得带有数字元素的行,则只需取消上述

cond[!grepl('^\\D*$', cond$Q26),, drop=FALSE]

数据

cond <- data.frame(Q26 = c(1, 1, '', 'Q26', 'Click to write the question text', 1),
                           stringsAsFactors=FALSE)
相关问题