Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

sapply

There is a strange behaviour of sapply() when used on a vector of characters:

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"

Why does sapply() return a vector with the old values as attributes? I don't want them, I don't need them and I am not aware of this behaviour when applied on e.g. numerical vectors.

like image 265
MERose Avatar asked Oct 22 '25 06:10

MERose


1 Answers

By default, sapply() adds names for each iteration on character vectors. The result can be delivered without the names by using USE.NAMES = FALSE in the call.

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

This is explained in 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.

Note that when you are applying a single function only, there is no need to use an anonymous function (anonymous function usage is also slightly less efficient). This is also shown above.

Also note that sapply() is not necessary here, as toupper() is vectorized.

toupper(y)
# [1] "HELLO" "BOB"   "DAN"  
like image 106
Rich Scriven Avatar answered Oct 23 '25 22:10

Rich Scriven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!