Ponder Stibbons
Ponder Stibbons

Reputation: 125

lapply does not seem to be a pure map function (or is this a string problem)?

I am using R 3.5.2.

As I read the documentation, I was expecting

lapply(c(a,b),f) == c(f(a),f(b))

But I get ...

f = function(x) x

b = c("1","0","0")

lapply(b,f)

[[1]]
[1] "1"

[[2]]
[1] "0"

[[3]]
[1] "0"

While I also get

c(f("1"),f("0"),f("0"))
[1] "1" "0" "0"e

I tried using sapply and got a different problem ...

sapply(c("1","0","0"),f)

 1   0   0 
"1" "0" "0" 

But sapply works on a numeric list ...

sapply(c(1,0,0),f)
[1] 1 0 0

So, how do I get just c(f(a),f(b)), generically ?

Upvotes: 1

Views: 40

Answers (1)

akrun
akrun

Reputation: 887028

The USE.NAMES argument in sapply is TRUE by default. It can be set to FALSE

sapply(c("1","0","0"),f, USE.NAMES = FALSE)
#[1] "1" "0" "0"

Or other options are wrap with unname or as.vector or unlist as all of these strips off the attribute. The output of sapply in OP's post is a named vector i.e. it includes the name as attributes. By wrapping with unname, as.vector, it removes the attribute

unname(sapply(c("1", "0", "0"), f))
#[1] "1" "0" "0"

Upvotes: 1

Related Questions