为什么 sapply() return 用于字符时带有属性的列表?

Why does sapply() return a list with attributes when used on characters?

sapply() 用于字符向量时有一个奇怪的行为:

y <- c("Hello", "bob", "daN")
z <- sapply(y, function(x) {toupper(x)})
z
# Hello     bob     daN 
# "HELLO"   "BOB"   "DAN" 
str(z)
# Named chr [1:3] "HELLO" "BOB" "DAN"
# - attr(*, "names")= chr [1:3] "Hello" "bob" "daN"

为什么 sapply() return 一个以旧值作为属性的向量?我不想要它们,我不需要它们,而且我不知道这种行为,例如应用于数值向量。

默认情况下,sapply() 为字符向量的每次迭代添加名称。 通过在调用中使用 USE.NAMES = FALSE,可以在没有名称的情况下传递结果。

sapply(y, toupper, USE.NAMES = FALSE)
# [1] "HELLO" "BOB"   "DAN" 

这在help(sapply)

中有解释

USE.NAMES - logical; if TRUE and if X is character, use X as names for the result unless it had names already. Since this argument follows ... its name cannot be abbreviated.

注意当你只应用单个函数时,没有必要使用匿名函数(匿名函数的使用效率也略低)。这也显示在上面。

另请注意 这里不需要 sapply(),因为 toupper() 已矢量化。

toupper(y)
# [1] "HELLO" "BOB"   "DAN"