简体   繁体   中英

R - lapply several functions in one lapply by elements

In R, when I run two functions in lapply , it runs the first function on the entire list, then run the second function on the list. Is it possible to force it runs both functions on the first element on the list before moving onto the second element?

I am using the function print and nchar for illustration purpose -- I wrote more complex functions that generate data.frame.

  lapply(c("a","bb","cdd"), function(x) {
    print(x)
    nchar(x)
  })

the output would be

[1] "a"
[1] "bb"
[1] "cdd"
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

I would like to have something like this:

[[1]]
[1] "a"
[1] 1

[[2]]
[1] "bb"
[1] 2

[[3]]
[1] "cdd"
[1] 3

is this possible?

Juan Antonio Roladan Diaz and cash2 both suggested using list , which kind of works:

lapply(c("a","bb","cdd"), function(x) { 
  list(x, nchar(x))
})

[[1]]
[[1]][[1]]
[1] "a"

[[1]][[2]]
[1] 1


[[2]]
[[2]][[1]]
[1] "bb"

[[2]][[2]]
[1] 2


[[3]]
[[3]][[1]]
[1] "cdd"

[[3]][[2]]
[1] 3

But it is a bit too messy.

using print gives a better result,

lapply(c("a","bb","cdd"), function(x) { 
  print(x)
  print(nchar(x))
  })

[1] "a"
[1] 1
[1] "bb"
[1] 2
[1] "cdd"
[1] 3
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

but is there a way to suppress nchar from being print out again?

This happens because the function prints x, then returns nchar(x) ; the returned elements are put into a list by lapply and returned, and printed out on the REPL.

Replace nchar(x) with print(nchar(x)) . Or, if you want the list returned, just return list(x, nchar(x)) from the inner function.

invisible(lapply(c("a","bb","cdd"), function(x) { print(x); print(nchar(x)) }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM