0

I am using this function I wrote to apply over all the columns in the flights data frame, from nycflights13. I want to remove the NA values that occur in each row, yet keep the same structure as the output shows. How would I go about doing that?

checker <- function(x){
  if(is.numeric(x)){
    max.x <- max(x, na.rm = TRUE)
    min.x <- min(x, na.rm = TRUE)
    vectorlist <- list(max=max.x, min=min.x)
    return(vectorlist)
  } else vectorlist <- list(max = NA, min = NA)
  return(vectorlist)
}
flightlist <- t(sapply(flights, checker))
flightlist

Hannah
  • 67
  • 8
  • Please do not post an image of code/data/errors, just the text itself. Several reasons are immediate: I cannot copy code or data from your image into my R console and try it out, and I choose to not transcribe it manually. Some reasons are slightly less obvious but still important, including: it breaks screen readers *hard*; search engines don't read them, so searches will not find it; mobile device screen size might be a limiting factor. Ref: https://meta.stackoverflow.com/a/285557/3358272 – r2evans Oct 16 '18 at 00:31
  • How should I display the output? – Hannah Oct 16 '18 at 00:34
  • If it's in R, then `dput(x)` (or `dput(head(x))` if large). If not, then make a fake structure in R (manually) and then use `dput`. Refs: https://stackoverflow.com/questions/5963269, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/tags/r/info. – r2evans Oct 16 '18 at 00:35
  • The data is a list. – Hannah Oct 16 '18 at 00:35
  • But lastly, if what you want is a *portrayal* of the data without the `NA` (i.e., in a report), then what you might think about is not how to remove it from the data, instead how to convince the relevant printing function what to do. For instance, `write.table(..., na="")`, `readr::write_csv(..., na="")`, or `knitr::kable(..., na=""); knitr::kable(...)`. – r2evans Oct 16 '18 at 00:37
  • I have to remove the rows with NA values present – Hannah Oct 16 '18 at 00:43
  • btw: `"NA"` is not the same as `NA`, the latter is a specific keyword in R that means "could be anything", "not applicable", "I could not calculate", etc. – r2evans Oct 16 '18 at 00:46
  • Why not `... else vectorlist <- list(max = "", min = "")`? You add the literal string yourself. – r2evans Oct 16 '18 at 00:49
  • That was my mistake in the function, I defined it as "NA" instead of NA – Hannah Oct 16 '18 at 00:49
  • You'll still have `NA` (vice `"NA"`) on the screen, are you trying to remove it for aesthetic purposes or because you don't like it on your R console? – r2evans Oct 16 '18 at 00:50
  • aesthetic purposes – Hannah Oct 16 '18 at 00:51
  • `cat(apply(cbind(rownames(flightlist), flightlist), 1, function(s) do.call(sprintf, c(list("%-20s %8s %8s\n"), s))))` – r2evans Oct 16 '18 at 00:56

0 Answers0