Subsetting R data frame results in mysterious NA rows

Wrap the condition in which: df[which(df$number1 < df$number2), ] How it works: It returns the row numbers where the condition matches (where the condition is TRUE) and subsets the data frame on those rows accordingly. Say that: which(df$number1 < df$number2) returns row numbers 1, 2, 3, 4 and 5. As such, writing: df[which(df$number1 < df$number2), … Read more

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