在R中,如何将变量(A,B和C)放在同一列中,例如A和B以及A和C放在同一面板中?

问题描述 投票:0回答:1

我有一个数据集。

df=tibble::tibble(
   cultivar=rep(c("cv1", "cv2", "cv3"), each = 5L),
   treatment=rep(c("Control", "Type 1", "Type 2", "Type 3", "Type 4"), 3),
   weight=c(10.6475, 25.355, 34.455, 40.355, 49.4225, 11.33571, 26.47, 31.04, 34.59167,
    49.00857, 14.03, 32.5, 19.73, 47.705, 56.74),
    std_err = c(
    1.111796, 1.232541, 3.174625, 2.887711, 1.478566, 1.244666, 2.491744,
    4.798628, 5.259148, 4.009993, 0.62, 0.6, 1.34, 0.015, 2.32
  ),
)

df
   cultivar treatment  weight std_err
 1 cv1      Control      10.6   1.11 
 2 cv1      Type 1       25.4   1.23 
 3 cv1      Type 2       34.5   3.17 
 4 cv1      Type 3       40.4   2.89 
 5 cv1      Type 4       49.4   1.48 
 6 cv2      Control      11.3   1.24 
 7 cv2      Type 1       26.5   2.49 
 8 cv2      Type 2       31.0   4.80 
 9 cv2      Type 3       34.6   5.26 
10 cv2      Type 4       49.0   4.01 
11 cv3      Control      14.0   0.62 
12 cv3      Type 1       32.5   0.6  
13 cv3      Type 2       19.7   1.34 
14 cv3      Type 3       47.7   0.015
15 cv3      Type 4       56.7   2.32 

我想在 cv1 和 cv2 之间以及 cv1 和 cv3 之间创建一个回归图。我想在一个面板中放置两条回归线。另外,我想在每个数据点中添加标准误差。

在 Excel 中,我可以创建如下图所示的图表。我想知道如何使用 R 来做到这一点?我相信有一些代码无需转置数据即可使用。

你能告诉我该怎么做吗?

非常感谢,

r regression data-fitting
1个回答
0
投票

这是一个基于将您的

"cv1"
加入到其他
cultivar
的 tidyverse 解决方案:

library(dplyr)
library(ggplot2)

left_join(
    filter(df, cultivar == "cv1"),
    filter(df, cultivar != "cv1"),
    join_by(treatment),
    suffix = c("", ".other")
  ) %>% 
  mutate(pair = paste0(cultivar, "-", cultivar.other)) %>% 
  ggplot(aes(weight, weight.other, color = pair)) +
  geom_errorbar(
    aes(ymin = weight.other - std_err.other, ymax = weight.other + std_err.other),
    width = 1,
    linewidth = 0.2,
    color = "black"
  ) +
  geom_errorbarh(
    aes(xmin = weight - std_err, xmax = weight + std_err),
    height = 1,
    linewidth = 0.2,
    color = "black"
  ) +
  geom_point() +
  geom_smooth(method = lm, se = FALSE, linewidth = 0.5) +
  coord_fixed() +
  theme_classic()

© www.soinside.com 2019 - 2024. All rights reserved.