ifelse和reorder函数

作者: 谢俊飞 | 来源:发表于2021-10-11 00:06 被阅读0次

ifelse()函数

Usage
ifelse(test, yes, no)
有三个参数。第一个参数test是一个逻辑向量,如果test为TRUE,函数结果就是第二个参数yes的值;如果test为FALSE,函数结果就是第三个参数no的值。

> x <- c(6:-4)
> x
 [1]  6  5  4  3  2  1  0 -1 -2 -3 -4
> sqrt(x)  #- gives warning
 [1] 2.449490 2.236068 2.000000 1.732051 1.414214 1.000000 0.000000      NaN
 [9]      NaN      NaN      NaN
Warning message:
In sqrt(x) : NaNs produced
> sqrt(ifelse(x >= 0, x, NA))  # no warning
 [1] 2.449490 2.236068 2.000000 1.732051 1.414214 1.000000 0.000000       NA
 [9]       NA       NA       NA

reorder()函数

Usage
Default S3 method:
reorder(x, X, FUN = mean, ...,
order = is.ordered(x))
Reorder是一个通用函数。“默认”方法将其第一个参数视为分类变量,并根据第二个变量(通常是数值变量)的值重新排列其级别。
FUN:一个函数,其第一个参数是一个向量,并返回一个标量,用于由X的级别决定的x的每个子集。

ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
  geom_boxplot()
image.png
ggplot(data = mpg) +
  geom_boxplot(
    mapping = aes(
      x = reorder(class, hwy, FUN = mean),
      y = hwy)
  )
image.png

相关文章

网友评论

    本文标题:ifelse和reorder函数

    本文链接:https://www.haomeiwen.com/subject/pddkoltx.html