首页 > 解决方案 > 如何根据 ifelse 语句中的条件返回向量或字符串?

问题描述

我正在尝试编写一个创建散点图的函数 - 其中的点可能需要根据变量着色或不着色。

我尝试了以下方法。但它不会按组对点进行着色。尽管代码在没有 ifelse 语句的情况下运行良好。

data <- data.frame(x = rnorm(100,sd=2),
           y1 = x*0.5+rnorm(100,sd=1),
           y2 = fitted(lm(y~x))) %>%
  pivot_longer(cols = -x,
               names_to = "Group",
               values_to = "yy")

group <- "Group"
ygroups <- 2
defaultcol = "black"


ggplot(data = data, mapping = aes(x = x , y = yy,
                                  color = ifelse(ygroups > 1, get(group), defaultcol))) +
  geom_point()

# runs fine
ggplot(data = data, mapping = aes(x = x , y = yy, color = get(group))) +
  geom_point()

标签: rggplot2

解决方案


您不想ifelse在这种情况下使用,因为您需要返回与输入长度不同的向量。只需使用普通的if/else

ggplot(data = data) + 
  aes(x = x , y = yy, color = if(ygroups > 1) get(group) else defaultcol) +
  geom_point() + 
  labs(color="Color")

但是您不能在其中设置特定的默认颜色aes(color=)- 这将通过您的色标重新映射颜色名称。如果您只想有条件地添加比例,那么请执行

ggplot(data = data) + 
  aes(x = x , y = yy) + 
  {if( ygroups > 1) aes(color=.data[[group]])} +
  geom_point()

.data[[ ]]建议使用优于使用get()


推荐阅读