Home > database >  Cann't remove NAs
Cann't remove NAs

Time:04-22

I am trying to delete rows in my dataset, which contains NAs, but none of the functions work, What could be a reason? Here is sample of my code,

Site_cov<- read.csv("site_cov.csv")
colnames(Site_cov)<- c("Point", "Basal", "Short.Saps", "Tall.Saps")
head(Site_cov)
 Point Basal Short.Saps Tall.Saps
1 DEL001    Na          2         0
2 DEL002    Na          1         6
3 DEL003    Na          0         5
4 DEL004    10         21        22

Here, I though that upper and lower case Nas, could be a problem and this is what I run,

Site_cov$Basal<-toupper(Site_cov$Basal)
Site_cov$Short.Saps<-toupper(Site_cov$Short.Saps)
Site_cov$Tall.Saps<-toupper(Site_cov$Tall.Saps)

Then, I try to delete NAs

Site_cov_NA <- Site_cov[complete.cases(Site_cov[ , c("Point", "Basal", "Short.Saps", "Tall.Saps")]), ]

But, NAs are still here

head(Site_cov_NA)

  Point Basal Short.Saps Tall.Saps
1 DEL001    NA          2         0
2 DEL002    NA          1         6
3 DEL003    NA          0         5
4 DEL004    10         21        22
5 DEL005    60          8        17
6 DEL006    80         17        13

CodePudding user response:

Obviously you have 'Na' strings that are fake NAs. replace them with real ones, then your code should work.

dat <- replace(dat, dat == 'Na', NA)
dat[complete.cases(dat[, c("Point", "Basal", "Short.Saps", "Tall.Saps")]), ]
#    Point Basal Short.Saps Tall.Saps
# 4 DEL004    10         21        22

Data:

dat <- structure(list(Point = c("DEL001", "DEL002", "DEL003", "DEL004"
), Basal = c("Na", "Na", "Na", "10"), Short.Saps = c(2L, 1L, 
0L, 21L), Tall.Saps = c(0L, 6L, 5L, 22L)), class = "data.frame", row.names = c("1", 
"2", "3", "4"))

CodePudding user response:

Try the complete.cases() function (https://stat.ethz.ch/R-manual/R-patched/library/stats/html/complete.cases.html)

try <- data.frame("a"=c(1,3,NA,NA), "b"=c(3,5,2,3))
try1<-try[complete.cases(try),]
try1
  •  Tags:  
  • r
  • Related