user297850
user297850

Reputation: 8015

function usage and output of lapply

I am trying to play with function of lapply

lapply(1:3, function(i) print(i))
# [1] 1
# [1] 2
# [1] 3
# [[1]]
# [1] 1

# [[2]]
# [1] 2

# [[3]]
# [1] 3

I understand that lapply should be able to perform print (i) against each element i among 1:3 But why the output looks like this.

Besides, when I use unlist, I get the output like the following

unlist(lapply(1:3, function(i) print(i)))
# [1] 1
# [1] 2
# [1] 3
# [1] 1 2 3

Upvotes: 0

Views: 236

Answers (1)

marbel
marbel

Reputation: 7714

The description of lapply function is the following:

"lapply returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X."

Your example:

lapply(1:3, function(x) print(x))

Prints the object x and returns a list of length 3.

str(lapply(1:3, function(x) print(x)))
# [1] 1
# [1] 2
# [1] 3
# List of 3
# $ : int 1
# $ : int 2
# $ : int 3

There are a few ways to avoid this as mentioned in the comments:

1) Using invisible

lapply(1:3, function(x) invisible(x))
# [[1]]
# [1] 1

# [[2]]
# [1] 2

# [[3]]
# [1] 3

unlist(lapply(1:3, function(x) invisible(x)))
# [1] 1 2 3

2) Without explicitly printing inside the function

unlist(lapply(1:3, function(x) x))
# [1] 1 2 3

3) Assining the list to an object:

l1 <- lapply(1:3, function(x) print(x))
unlist(l1)
# [1] 1 2 3

Upvotes: 1

Related Questions