r - 如何根据 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()
解决方案
您不想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()
)
推荐阅读
- cakephp - 从 3.6.6 升级到 3.7.5 后 PHPUnit 测试断言不同
- python - 使用 Python f-strings 生成 Python 代码是否有效?
- mysql - 有没有办法优化这个查询?在 MySQL 中加入多行
- kubernetes - 多区集群 ETCD 架构
- c# - 重载方法而不修改类
- reactjs - 在 React Native 中使用 !important
- json - 将变量传递给 Step Function start_execution() 输入参数
- android - 如何解决 tflte 中运行方法出现空指针的错误
- python - 在 Kubernetes 中通过代码创建文件
- arrays - 包含所有元素而不使用数组的最短子数组?