admin管理员组

文章数量:1599531

the condition has length > 1 and only the first element will be used

目录

the condition has length > 1 and only the first element will be used

问题:

解决:

完成错误:


问题:

有一个接受多个参数的函数。希望将函数元素应用于向量并获得向量结果。

不幸的是,函数没有向量化;也就是说,它对标量起作用,但对向量不起作用。

#

gcd <- function(a, b) {
  if (b == 0) {
    return(a)
  } else {
    return(gcd(b, a %% b))
  }
}

gcd(c(1, 2, 3), c(9, 6, 3))

> gcd <- function(a, b) {
+     if (b == 0) {
+         return(a)
+     } else {
+         return(gcd(b, a %% b))
+     }
+ }

> gcd(c(1, 2, 3), c(9, 6, 3))
[1] 1 2 0
Warning messages:
1: In if (b == 0) { :
  the condition has length > 1 and only the first element will be used
2: In if (b == 0) { :
  the condition has length > 1 and only the first element will be used
3: In if (b == 0) { :
  the condition has length > 1 and only the first element will be used
>  

解决:

有一个接受多个参数的函数。希望将函数元素应用于向量并获得向量结果。不幸的是,函数没有向量化;也就是说,它对标量起作用,但对向量不起作用。

使用tidyverse核心包purrr中的一个map或pmap函数。

最一般的解决方案是将向量放在一个列表中,然后使用pmap函数;

lst <- list(v1, v2, v3)
pmap(lst, fun)

如果只有两个向量作为函数的输入传递,那么map2_*函数族非常方便,省去了将向量放在列表中的步骤。

map2将返回一个列表,而它的变体(map2_chr、map2_dbl等)返回其名称所暗示的类型的向量。

map2(v1, v2, fun)

因此如果函数fun只返回一个双精度型结果,则使用map2的变体

map2_dbl(v1, v2, fun)

gcd函数没有向量化,但我们可以使用map来“向量化”它。由于我们要映射两个输入,我们应该使用map2函数。这给出了两个向量之间的按元素的最大公约数(GCD)。

#

gcd <- function(a, b) {
  if (b == 0) {
    return(a)
  } else {
    return(gcd(b, a %% b))
  }
}


a <- c(1, 2, 3)
b <- c(9, 6, 3)
my_gcds <- map2(a, b, gcd)
my_gcds

unlist(my_gcds)

> gcd <- function(a, b) {
+     if (b == 0) {
+         return(a)
+     } else {
+         return(gcd(b, a %% b))
+     }
+ }


> a <- c(1, 2, 3)
> b <- c(9, 6, 3)
> my_gcds <- map2(a, b, gcd)
> my_gcds
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3


> unlist(my_gcds)
[1] 1 2 3

完成错误:

> gcd <- function(a, b) {
+     if (b == 0) {
+         return(a)
+     } else {
+         return(gcd(b, a %% b))
+     }
+ }

> gcd(c(1, 2, 3), c(9, 6, 3))
[1] 1 2 0
Warning messages:
1: In if (b == 0) { :
  the condition has length > 1 and only the first element will be used
2: In if (b == 0) { :
  the condition has length > 1 and only the first element will be used
3: In if (b == 0) { :
  the condition has length > 1 and only the first element will be used

本文标签: conditionlengthelement