If statement 如果ggplot+中有其他项;几何图形的字符和数字之间的切换值

If statement 如果ggplot+中有其他项;几何图形的字符和数字之间的切换值,if-statement,ggplot2,geom-vline,If Statement,Ggplot2,Geom Vline,我需要在ggplot中集成if-else块,根据变量到开关的值,它将: 如果值为数字->打印线 值为文本->不打印线 我以最完整的版本提供代码,以考虑与提供的解决方案可能存在的冲突 #创建数据---- obs_编号如评论中所述,主要问题是数据帧metrics_test中的xintercept列包含编号和文本。数据框列只能包含一种变量类型,文本不能是数字,因此此列将始终是chr类型,而不是num类型。然后将此列指定给geom_vline()调用中的xintercept美学,这就是错误消息的来

我需要在ggplot中集成
if-else
块,根据
变量到开关的值,它将:

  • 如果值为数字->打印线
  • 值为文本->不打印线
我以最完整的版本提供代码,以考虑与提供的解决方案可能存在的冲突


#创建数据----

obs_编号如评论中所述,主要问题是数据帧
metrics_test
中的
xintercept
列包含编号和文本。数据框列只能包含一种变量类型,文本不能是数字,因此此列将始终是
chr
类型,而不是
num
类型。然后将此列指定给
geom_vline()
调用中的
xintercept
美学,这就是错误消息的来源

如果您提供的数据帧子集在
metrics\u test$xintercept
中不包含文本值,则可以通过强制将列转换为数字类型来解决此问题,只要该列不再包含任何文本即可。在示例代码中,如果将代码的第一部分替换为以下内容,则不会出现错误:

# your code prior to the if/then statement...

if(variable_to_switch == "Text"){
  
  d <- metrics_test[c(6,7,9),]    # temporary data frame
  d$xintercept <- as.numeric(d$xintercept)
  
  histo_density_plot <- histo_density_plot +
    
    geom_vline(aes(xintercept = xintercept, color = label),
               data = d, linetype = "dashed", size = 0.5, alpha = 1,
               key_glyph = draw_key_text) +

    # the rest of the if then statement and code continues as you have it..
#if/then语句之前的代码。。。
if(变量到开关==“文本”){

d列
metrics\u test$xintercept
不是数字,因此出现错误。您不能将非数字值作为
xintercept
发送到
geom\u vline()
。无论如何,你不能从该数据集中绘制第6行,对吗?是的,我知道我不能发送非数字值。但这就是为什么有时它会是非数字的。同时,我只对
if
else
块使用了两种不同的代码。这是多余的,但有效。我想知道是否有更优雅的代码这类案件的和解。
# your code prior to the if/then statement...

if(variable_to_switch == "Text"){
  
  d <- metrics_test[c(6,7,9),]    # temporary data frame
  d$xintercept <- as.numeric(d$xintercept)
  
  histo_density_plot <- histo_density_plot +
    
    geom_vline(aes(xintercept = xintercept, color = label),
               data = d, linetype = "dashed", size = 0.5, alpha = 1,
               key_glyph = draw_key_text) +

    # the rest of the if then statement and code continues as you have it..