使用数据框 (R) 在应用函数中获取列名

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

这看起来很简单。但是我找不到一个简单快捷的解决方案来解决这个问题。 我只想 运行 在数据框上应用一个函数——结果应该按列显示一条包含列名的消息。我的其余命令工作正常...

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

它不显示每一列的名称。我怀疑这是因为它按列工作..我需要想出我自己的功能吗? 谢谢, 纳丁

您可以遍历 names:

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

或者在 for 循环中可能更好:

for(i in names(airquality)) {
  message(i," has ",sum(!is.na(airquality[[i]]))," cases.\n","NA values: ",
          length(airquality[[i]]) - sum(!is.na(airquality[[i]])))
}
#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

下面是我如何使用 purrr::iwalk():

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

输出:

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