可能重复:
R - 在data.frame中删除具有NA的行
我有一个名为sub.new的数据框,其中包含多个列.我试图排除任何包含NA或blank space" ".
I tried to use subset(),但它的目标是特定的列条件.无论如何都要扫描整个数据帧并创建一个没有单元格的子集NA或者blank space?
在下面的示例中,只应保留第一行:
# ID SNP ILMN_Strand Customer_Strand
ID1234 [A/G] TOP BOT
Non-Specific NSB (Bgnd) Green
Non-Polymorphic NP (A) Red
Non-Polymorphic NP (T) Purple
Non-Polymorphic NP (C) Green
Non-Polymorphic NP (G) Blue
Restoration Restore Green
Run Code Online (Sandbox Code Playgroud)
有什么建议?谢谢
Ali*_*Ali 54
一个好主意是在进行任何进一步分析之前将所有""(空白单元格)设置为NA.
如果您正在从文件中读取输入,那么将所有""强制转换为NAs是一个不错的选择:
foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited
Run Code Online (Sandbox Code Playgroud)
如果您已经加载了表,则可以执行以下操作:
foo[foo==""] <- NA
Run Code Online (Sandbox Code Playgroud)
然后,为了只保留没有NA的行,你可以使用na.omit():
foo <- na.omit(foo)
Run Code Online (Sandbox Code Playgroud)
或者保持没有NA的列:
foo <- foo[, colSums(is.na(foo)) == 0]
Run Code Online (Sandbox Code Playgroud)
And*_*rej 11
不知道你究竟是什么类型的数据集,所以我提供一般答案.
x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
x y
1 1 1
2 2 2
3 NA 3
4 3 NA
5 4 6
6 5 8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
x y
1 1 1
2 2 2
5 4 6
6 5 8
Run Code Online (Sandbox Code Playgroud)