Search code examples
rnames

Get column names in apply function with data frame (R)


This seems easy. But I cannot find an easy and quick solution to this thing. I just want to run an apply function on a data frame - the result should show columnwise a message containing the column name. The rest of my command is working fine...

apply(airquality, 2, function(x) message(names(x)," has ",sum(!is.na(x))," cases.\n","NA values: ",
                                         length(x) - sum(!is.na(x))))

It does not show the name of each column. I suspect that this is because it works columnwise.. do I need to come up with my own function? Thanks, Nadine


Solution

  • Here is how I would do it with purrr::iwalk():

    purrr::iwalk(airquality, ~ message(sprintf("%s has %s cases.\nNA values: %s",
                                               .y,
                                               sum(!is.na(.x)),
                                               sum(is.na(.x)))))
    

    Output:

    Ozone has 116 cases.
    NA values: 37
    Solar.R has 146 cases.
    NA values: 7
    Wind has 153 cases.
    NA values: 0
    Temp has 153 cases.
    NA values: 0
    Month has 153 cases.
    NA values: 0
    Day has 153 cases.
    NA values: 0