我對這個功能有疑問(我是 R 新手)
我想創建一個簡單的函式,在其中插入一個基因(變數)以獲得一個簡單的箱線圖來比較兩個條件(條件),但是我獲得了兩條平線并且不知道為什么。在函式中,我想在 x 軸上有“條件”,在 y 軸上有變數的值,并且我最初從 df 中洗掉了 na 值,但我認為這不是問題所在。
funzione <- function(variabile) {
tab <- tab_n %>% filter(!is.na(Condition))
tab %>% ggplot(aes(x = Condition, y = variabile, fill = Condition))
geom_boxplot(alpha = 0.5)
geom_point(position = position_dodge(width=0.75))
ggpubr::stat_compare_means(aes(group = Condition), label.x.npc = "center", size = 3.2)
theme_bw()
}
這是我擁有的資料庫的第一行。
| 性別 | 健康)狀況 | variable_to_insert |
|---|---|---|
| 男性 | cond_1 | 5.6 |
| 女性 | cond_1 | 4.7 |
| 女性 | cond_2 | 4.8 |
| 女性 | cond_1 | 5.8 |
| 男性 | cond_2 | 5.1 |
| 女性 | cond_1 | 5.5 |
| 男性 | cond_2 | 7.9 |
| 男性 | cond_2 | 7.1 |
| 女性 | cond_1 | 2.9 |
uj5u.com熱心網友回復:
下面的函式被重寫以接受 data.frame 和變數作為引數。
library(dplyr)
library(ggplot2)
funzione <- function(x, variabile) {
x %>%
filter(!is.na(Condition)) %>%
ggplot(aes(x = Condition, y = {{variabile}}, fill = Condition))
geom_boxplot(alpha = 0.5)
geom_point(position = position_dodge(width=0.75))
ggpubr::stat_compare_means(aes(group = Condition), label.x.npc = "center", size = 3.2)
theme_bw()
}
tab_n %>% funzione(variable_to_insert)

由reprex 包于 2022-02-14 創建(v2.0.1)
資料
tab_n <- read.table(text = "
Gender Condition variable_to_insert
Male cond_1 5.6
Female cond_1 4.7
Female cond_2 4.8
Female cond_1 5.8
Male cond_2 5.1
Female cond_1 5.5
Male cond_2 7.9
Male cond_2 7.1
Female cond_1 2.9
", header = TRUE)
由reprex 包于 2022-02-14 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427659.html
