Replace NA in column with value in adjacent column

It didn’t work because status was a factor. When you mix factor with numeric then numeric is the least restrictive. By forcing status to be character you get the results you’re after and the column is now a character vector: TEST$UNIT[is.na(TEST$UNIT)] <- as.character(TEST$STATUS[is.na(TEST$UNIT)]) ## UNIT STATUS TERMINATED START STOP ## 1 ACTIVE ACTIVE 1999-07-06 2007-04-23 … Read more

suppress NAs in paste()

For the purpose of a “true-NA”: Seems the most direct route is just to modify the value returned by paste2 to be NA when the value is “” paste3 <- function(…,sep=”, “) { L <- list(…) L <- lapply(L,function(x) {x[is.na(x)] <- “”; x}) ret <-gsub(paste0(“(^”,sep,”|”,sep,”$)”),””, gsub(paste0(sep,sep),sep, do.call(paste,c(L,list(sep=sep))))) is.na(ret) <- ret==”” ret } val<- paste3(c(“a”,”b”, “c”, … Read more

How to replace NA with mean by group / subset?

Not my own technique I saw it on the boards a while back: dat <- read.table(text = “id taxa length width 101 collembola 2.1 0.9 102 mite 0.9 0.7 103 mite 1.1 0.8 104 collembola NA NA 105 collembola 1.5 0.5 106 mite NA NA”, header=TRUE) library(plyr) impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = … Read more