[英]R - Delete column if last value is NA
I want to delete column(s) in R data frame if their last value is NA. 如果最后一个值为NA,我想删除R数据帧中的列。
Example data frame is below 示例数据框如下
A B C D
11 10 19 20
22 20 29 40
33 30 39 60
44 NA NA 80
I would like to get the following output (Column B and C dropped because they had NA values in the last row) 我想获得以下输出(列B和C被删除,因为它们在最后一行中有NA值)
A D
11 20
22 40
33 60
44 80
Tried but couldn't get any solution to work. 尝试但无法获得任何解决方案。 Appreciate your help.
感谢您的帮助。
# Data
df <- read.table(text="A B C D
11 10 19 20
22 20 29 40
33 30 39 60
44 NA NA 80", header=TRUE)
df[-which(is.na(df[nrow(df), ]))]
A D
1 11 20
2 22 40
3 33 60
4 44 80
# Suggestion from @alistaire
df[, !is.na(df[nrow(df), ])]
na.omit() function deletes any rows with missing data. na.omit()函数删除任何缺少数据的行。 pp <- data.frame(po=c(10,20,30,40,NA), pi=c(45,65,75,55,85)) pp na.omit(pp) -- deletes the entire row
pp < - data.frame(po = c(10,20,30,40,NA),pi = c(45,65,75,55,85))pp na.omit(pp) - 删除整行
na.delete(pp["po"]) --- deletes the entire column with "NA". na.delete(pp [“po”])---用“NA”删除整个列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.