R中的分组箱线图

Grouped boxplot in R

df <- data.frame(values = c(2.5,12,4.8,56,78),samples = c('45fe.K2','59ji.K2','59rc.K1','45hi.K1','96hu.K1'),group = c('K2','K2','K1','K1','K1'))

 df
  values samples group
1    2.5 45fe.K2    K2
2   12.0 59ji.K2    K2
3    4.8 59rc.K1    K1
4   56.0 45hi.K1    K1
5   78.0 96hu.K1    K1

我想生成一个 group 分组箱线图。所以我想要一个带有 K1K2 箱线图的图。我认为这个 https://www.r-graph-gallery.com/265-grouped-boxplot-with-ggplot2.html 可以做到,但我不知道怎么做

p1 <- ggplot(df, aes(x=group, y=values, fill=group)) + 
    geom_boxplot() +
    facet_wrap(~group)

我该怎么办?我也试过 x=samples 但那是错误的。

编辑:也许这是另一个问题。但是,当我使用以下代码添加 group 列时,@rodolfoksveiga 的出色回答会导致错误

df <- data.frame(values = c(2.5, 12, 4.8, 56, 78),
samples = c('45fe.K2', '59ji.K2', '59rc.K1', '45hi.K1', '96hu.K1'))

df$group <- NA
df$group <- apply(df,1,function(x)
{ifelse(grepl('K2',df$samples) == TRUE,paste('K2'),paste('K1'))})

Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = c(1L, 2L, 2L, 2L,  : 
 replacement has ... rows, data has ....rows

欢迎来到 Stack Overflow Joris。

也许这就是你想要的:

library(ggplot2)
df <- data.frame(values = c(2.5, 12, 4.8, 56, 78),
                 samples = c('45fe.K2', '59ji.K2', '59rc.K1', '45hi.K1', '96hu.K1'),
                 group = c('K2', 'K2', 'K1', 'K1', 'K1'))
ggplot(df, aes(x = group, y = values, fill = group)) + 
  geom_boxplot() +
  facet_wrap(. ~ group, scales = 'free_x')

这是输出:

如果这就是您要找的,请告诉我们。