大家好,
library(dplyr)
library(tibble)
mtcars %>%
rownames_to_column("modelle") %>%
mutate_if(~is.numeric(.x) & mean(.x) > 50, ~(.x / 1000))
Warning message:
In mean.default(.x) : argument is not numeric or logical: returning NA这个错误似乎是因为字符向量。很管用,但还是很难看。我做错什么了吗?在这种情况下还有什么可以做得更好的呢?
谢谢!
发布于 2020-02-16 06:52:13
R没有短路矢量化的&,所以这是同时运行is.numeric和mean的所有列.因为您的第一列(modelle)显然是character,所以它失败了。
但是,您实际上不需要将其向量化。如果你从矢量化的&变成二进制的&&,R短路,你就得到了你想要的行为。
mtcars %>%
rownames_to_column("modelle") %>%
mutate_if(~is.numeric(.x) && mean(.x) > 50, ~(.x / 1000)) %>%
head()
# modelle mpg cyl disp hp drat wt qsec vs am gear carb
# 1 Mazda RX4 21.0 6 0.160 0.110 3.90 2.620 16.46 0 1 4 4
# 2 Mazda RX4 Wag 21.0 6 0.160 0.110 3.90 2.875 17.02 0 1 4 4
# 3 Datsun 710 22.8 4 0.108 0.093 3.85 2.320 18.61 1 1 4 1
# 4 Hornet 4 Drive 21.4 6 0.258 0.110 3.08 3.215 19.44 1 0 3 1
# 5 Hornet Sportabout 18.7 8 0.360 0.175 3.15 3.440 17.02 0 0 3 2
# 6 Valiant 18.1 6 0.225 0.105 2.76 3.460 20.22 1 0 3 1进一步证明&不是短路.
mymean <- function(x, ...) {
if (is.character(x)) {
message("character?")
return(Inf) # this is certainly not the right thing to do in general ...
} else mean(x, ...)
}
mtcars %>%
rownames_to_column("modelle") %>%
mutate_if(~is.numeric(.x) & mymean(.x) > 50, ~(.x / 1000)) %>%
head()
# character?
# modelle mpg cyl disp hp drat wt qsec vs am gear carb
# 1 Mazda RX4 21.0 6 0.160 0.110 3.90 2.620 16.46 0 1 4 4
# 2 Mazda RX4 Wag 21.0 6 0.160 0.110 3.90 2.875 17.02 0 1 4 4
# 3 Datsun 710 22.8 4 0.108 0.093 3.85 2.320 18.61 1 1 4 1
# 4 Hornet 4 Drive 21.4 6 0.258 0.110 3.08 3.215 19.44 1 0 3 1
# 5 Hornet Sportabout 18.7 8 0.360 0.175 3.15 3.440 17.02 0 0 3 2
# 6 Valiant 18.1 6 0.225 0.105 2.76 3.460 20.22 1 0 3 1如果发生短路,那么mymean将永远无法到达信息.(我不认为这个mymean在这里是可行的替代品,原因有以下几点:(1)使用Inf仅仅是为了确保调用mean之外的条件有效,但是如果发生错误/警告并且需要numeric,则通常应该返回NA或NaN,而不是数字.即使您可能不认为Inf是一个真正可用的数字。(2)它解决的是一种症状,而不是问题。问题是在矢量化的逻辑表达式中没有短路.)
发布于 2020-02-16 06:54:05
你应该使用"&“而不是”&“。第一个用于标量,第二个用于矢量。在你的例子中,平均值是一个标量。
library(dplyr)
library(tibble)
mtcars %>%
rownames_to_column("modelle") %>%
mutate_if(~is.numeric(.x) && mean(.x) > 50, ~(.x / 1000))https://stackoverflow.com/questions/60246025
复制相似问题