2012-07-16 176 views
1

我有一個721 x 26數據框。一些行具有空白的條目。它不是NULL 或NA,但只是空的如下。我如何刪除那些有這些條目的行?R中有空白條目的行

1   Y N  Y   N   86.8 
2   N N  Y   N   50.0 
3            76.8 
4   N N  Y   N   46.6 
5   Y Y  Y   Y   30.0 
+0

您是否試過'==「」'匹配空格? – Gregor 2012-07-16 22:46:06

+3

「空白」是什麼意思?請使用'dput()' – Andrie 2012-07-16 22:46:17

回答

5

這個問題的答案取決於你想要關於那些可能出現在'空白'字符串中的事情的偏執。這是一個非常小心的方法,它將匹配零長度的空字符串""以及任意由一個或多個[[:space:]]字符組成的字符串(即「製表符,換行符,垂直製表符,換頁符,回車符,空格以及可能還有其他符合語言環境的字符串字符「,根據?regex幫助頁面)。

## An example data.frame containing all sorts of 'blank' strings 
df <- data.frame(A = c("a", "", "\n", " ", " \t\t", "b"), 
       B = c("b", "b", "\t", " ", "\t\t\t", "d"), 
       C = 1:6) 

## Test each element to see if is either zero-length or contains just 
## space characters 
pat <- "^[[:space:]]*$" 
subdf <- df[-which(names(df) %in% "C")] # removes columns not involved in the test 
matches <- data.frame(lapply(subdf, function(x) grepl(pat, x))) 

## Subset df to remove rows fully composed of elements matching `pat` 
df[!apply(matches, 1, all),] 
# A B C 
# 1 a b 1 
# 2 b 2 
# 6 b d 6 

## OR, to remove rows with *any* blank entries 
df[!apply(matches, 1, any),] 
# A B C 
# 1 a b 1 
# 6 b d 6 
+0

發佈一些示例數據什麼是'grepl'函數? – Dombey 2012-07-16 23:16:55

+0

就像'grep',除了它返回所有匹配的「TRUE」和不匹配的'FALSE'。試試看:'grepl(「a」,c(「ab」,「b」,「c」,「a」))''。官方文檔另請參閱'?grepl'。 – 2012-07-16 23:20:33

+0

但是在結果數據集中仍然有一行有空格。 (2b2)。 – Dombey 2012-07-16 23:41:39