R 语言使用sapply , lapply 中 遇到问题 the condition has length > 1 and only the first element will be used
使用 lapply 中输入list , 如果自己编写的函数中存在 if 判断语句,会导致有时候会报错,举例子如下:
> rm(list=ls())
> Test <- function(x){
+ if(x == 1){
+ y = x+1
+ }else{
+ y = x+2
+ }
+ }
>
> Data1 = list(c(1,2,3))
> lapply(Data1,Test)
[[1]]
[1] 2 3 4
Warning message:
In if (x == 1) { :
the condition has length > 1 and only the first element will be used
>
> # 解决方法1
> Data2 = list(c(1,2,3))
> lapply(Data2[[1]],Test)
[[1]]
[1] 2
[[2]]
[1] 4
[[3]]
[1] 5
>
>
> # 解决方法2
> Data3 = c(1,2,3)
> lapply(Data3,Test)
[[1]]
[1] 2
[[2]]
[1] 4
[[3]]
[1] 5
>
>
> # 解决方法3,使用 ifelse 函数,这个就要修改原始的函数了
> Test2 <- function(x){
+ y = ifelse(x==1,x+1,x+2)
+ }
> lapply(Data1,Test2)
[[1]]
[1] 2 4 5
>
> # 如果ifelse 的语句有多个输出结果可以使用 list 函数进行连接
> Test3 <- function(x){
+ y <- ifelse(x==1,list(c(x+1,x+2,x+3)),0)
+ }
> lapply(Data1[[1]],Test3)
[[1]]
[[1]][[1]]
[1] 2 3 4
[[2]]
[1] 0
[[3]]
[1] 0

浙公网安备 33010602011771号