root <- c(54, 7, 125, 80, 0, 60, 30, 51, 23, 7)
smith <- c(112, 2, 104, 19, 7, 12, 61, 80, 4, 49)
kohli <- c(43, 31, 25, 186, 75, 37, 40, 1, 4, 130)
williamson <- c(22, 73, 98, 38, 61, 9, 22, 101, 0, 12)
batsmen <- list(root, smith, kohli, williamson)
bat_names <- c("Joe Root", "Steve Smith", "Virat Kohli", "Kane Williamson")
names(batsmen) <- bat_names
bat_averages <- function(x) {
paste(names(x), "average is", mean(x))
}
lapply(batsmen, bat_averages)
$`Joe Root`
[1] " average is 43.7"
$`Steve Smith`
[1] " average is 45"
$`Virat Kohli`
[1] " average is 57.2"
$`Kane Williamson`
[1] " average is 43.6"
如何在函数内的击球手中打印每个对象的名称?我想我理解为什么使用循环/不适用于names()的原因,但是我不知道如何获得所需的结果。非常感谢。