[英]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. 在R中,当我在lapply
运行两个函数时,它将在整个列表上运行第一个函数,然后在列表上运行第二个函数。 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. 我将函数print
和nchar
用于说明目的 -我编写了一些更复杂的函数来生成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: Juan Antonio Roladan Diaz和cash2都建议使用list
,这是一种工作:
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? 但是有办法抑制再次输出nchar
吗?
This happens because the function prints x, then returns nchar(x)
; 发生这种情况是因为该函数先打印x,然后返回nchar(x)
; the returned elements are put into a list by lapply
and returned, and printed out on the REPL. 返回的元素被lapply
放到列表中并返回,并打印在REPL上。
Replace nchar(x)
with print(nchar(x))
. 将nchar(x)
替换为print(nchar(x))
。 Or, if you want the list returned, just return list(x, nchar(x))
from the inner function. 或者,如果要返回list(x, nchar(x))
,只需从内部函数返回list(x, nchar(x))
。
invisible(lapply(c("a","bb","cdd"), function(x) { print(x); print(nchar(x)) }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.