0

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
2
  • 3
    yes, you get the printout and afterwards the object that is returned is printed implicitly. If you save the output in an object you will not see the second part. l <- lapply(1:5, function(x) print(i)) Commented Jan 12, 2014 at 17:55
  • 3
    Please do not use images to represent code. Commented Jan 12, 2014 at 18:09

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.