R 根据过滤后的数据分配geom_hline值,并将其作为同一代码块的一部分执行?

R 根据过滤后的数据分配geom_hline值,并将其作为同一代码块的一部分执行?,r,ggplot2,tidyverse,geom-hline,R,Ggplot2,Tidyverse,Geom Hline,我试图根据过滤数据和从一列中选择的值来分配geom_hline,但这一切都是在同一个代码块中完成的。我不知道最好的办法是什么——任何帮助都将不胜感激 样本数据: structure(list(sample_name = c("control1", "control2", "S01", "S02", "S03", "S04", "S05", "S0

我试图根据过滤数据和从一列中选择的值来分配geom_hline,但这一切都是在同一个代码块中完成的。我不知道最好的办法是什么——任何帮助都将不胜感激

样本数据:

structure(list(sample_name = c("control1", "control2", "S01", 
"S02", "S03", "S04", "S05", "S06", "S07", "S08"), estimate = c(1.703, 
5.553, 4.851, 5.257, 4.573, 3.278, 1.687, 3.628, 1.877, 5.826
), std.error = c(1.767, 2.382, 1.641, 1.062, 1.133, 1.477, 0.978, 
0.611, 1.893, 0.78), upper_limit_value = c(5.166, 10.223, 8.067, 
7.339, 6.795, 6.173, 3.605, 4.825, 5.586, 7.355), lower_limit_value = c(-1.761, 
0.884, 1.635, 3.175, 2.352, 0.384, -0.231, 2.431, -1.833, 4.298
)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))
在geom_hline()部分中,是否有一种方法可以定义y截距应基于过滤数据的内容-几乎像一个侧赋值

类似于

geom_hline(aes(yintercept = df %>% filter(sample_name="control1") %>% select("upper_limit_value"))) +
geom_hline(aes(yintercept = df %>% filter(sample_name="control1") %>% select("lower_limit_value")))
在本例中,sample_name=“control1”只有一行过滤数据,我试图使用“上限值”列下的值(以及“下限值”作为单独的几何图形线)

谢谢

尝试将
数据
参数中的数据子集:

完整的代码将变成以下代码

df %>%
  ggplot(aes(x=sample_name, y=estimate, group=sample_name, color=sample_name))+ 
  geom_point() +
  geom_hline(data = df %>% filter(sample_name == "control") %>% select(upper_limit_value),
             mapping = aes(yintercept = upper_limit_value))
(我不认为有必要
选择(上限值)
,但如果没有测试数据,很难说。)

另一个选项是在问题代码中使用
pull
,而不是
select
。不同之处在于,
select
返回包含这些列的数据集,
pull
返回列值

geom_hline(aes(yintercept = df %>% filter(sample_name == "control") %>% pull(upper_limit_value)))

编辑 我上面提到的数据转换是

df$sample_name[df$sample_name == "control2"] <- "control"

你能发布样本数据吗?请使用
dput(df)
的输出编辑问题。或者,如果输出的dput(head(df,20))
太大,谢谢!对于第二个选项geom_hline(aes(yintercept=df%>%filter(sample_name==“control”)%%>%pull(上限值)),为什么“df”不能是“?”??我收到以下错误“错误:美学必须是有效的数据列。有问题的美学:yintercept=
%%>%
(…)。您是否键入了数据列的名称错误,或者忘记在_stat()之后添加?”@dnmc尝试用点替换df名称,请参见。正如我所说,没有数据,我无法测试代码。哦,现在我看到了用代码编辑的问题。马上回来。@dnmc df有一个值
“control1”
和另一个值
“control”
,但没有
“control”
,过滤后它是一个零行TIBLE。啊-很抱歉弄错了,我在发布示例数据集之前更改了一些列名。如果我运行以下df%>%ggplot(,aes(x=sample\u name,y=estimate,group=sample\u name,color=sample\u name))+geom\u point()+geom\u hline(aes(yintercept=.%>%filter(sample\u name=“control1”)%>%pull(上限值)),我会得到错误:美学必须是有效的数据列。有问题的美学:yintercept=.%>%过滤器(示例名称==“control1”)%%>%pull(上限值)。您是否键入了数据列的名称错误,或者忘记在_stat()之后添加?忘记提到我正在管道化到ggplot,因为我计划对涉及转换的较大数据集执行其他操作:)
geom_hline(aes(yintercept = df %>% filter(sample_name == "control") %>% pull(upper_limit_value)))
df$sample_name[df$sample_name == "control2"] <- "control"
ggplot(df, aes(x=sample_name, y=estimate, group=sample_name, color=sample_name))+ 
  geom_point() +
  geom_hline(aes(yintercept = df %>% filter(sample_name == "control") %>% pull(upper_limit_value)))