我在R中有一个有5列的数据框.第一列是ID被拆分的两个组.接下来的4列是对问卷的回答,其中2列是连续变量,另外两列是分类变量.

library(dplyr)
# set random seed for reproducibility
set.seed(123)

# create first column with categorical variable with levels yes and no
col1 <- sample(c("yes", "no"), 20, replace = TRUE)

# create second and third columns with continuous variables
col2 <- rnorm(20, mean = 10, sd = 2)
col3 <- rnorm(20, mean = 5, sd = 1)

# create fourth and fifth columns with categorical variables
col4 <- sample(c("high", "low"), 20, replace = TRUE)
col5 <- sample(c("small", "big"), 20, replace = TRUE)

# combine all columns into a data frame
df <- tibble(col1, col2, col3, col4, col5)

# print the data frame
df

我想进行两个检验统计.如果变量(列)是连续的,则执行Mann Whitney U检验,如果变量是分类的,则创建列联表并执行卡方独立性检验.

例如,对于连续 case :

# perform Mann-Whitney U test on column 2, according to the two groups in column 1
test_result <- wilcox.test(df$col2 ~ df$col1)

# print the test result
print(test_result)

对于绝对的情况:


# create contingency table for columns 1 and 5
cont_table <- table(df[, 1], df[, 5])

# print the contingency table
print(cont_table)
# perform chi-squared test on the first and fifth columns
test_result2 <- chisq.test(cont_table)

但我希望这一列都在管道下执行,以判断列是绝对的还是连续的(数值),并执行我想要的相应测试.我想用dplyr包来做这件事,并且只总结p值.

我怎样才能在R中做到这一点?

推荐答案

您可以将summarizeacross和一个条件lambda函数相加:

df %>%
  summarise(across(col2:col5, function(.x) {
    if(is.numeric(.x)) {
      wilcox.test(.x[col1 == "yes"], .x[col1 == "no"])$p.v
    } else {
      suppressWarnings(chisq.test(table(.x, col1))$p.v)
    }
  }))
#> # A tibble: 1 x 4
#>    col2  col3  col4  col5
#>   <dbl> <dbl> <dbl> <dbl>
#> 1 0.766 0.882     1 0.619

创建于2023-03-19年第reprex v2.0.2

R相关问答推荐

R根据名称的载体对收件箱列采取行动

根据列中的数字移动单元格位置

图片中令人惊讶的行为

将虚线添加到每个站点的传奇中平均

如何按照特定顺序拆分字符?

在R中,如何创建时间间隔的图表?

如何在编辑列时更新可编辑数据表,并使用该表在Shiny中执行连续计算

如何在区分不同条件的同时可视化跨时间的连续变量?

对于变量的每个值,仅 Select 包含列表中所有值的值.R

将饼图插入条形图

从外部文件读取多个值作为字符向量

在嵌套列表中查找元素路径的最佳方法

如何写商,水平线,在一个单元格的表在R

ComplexHEAT:使用COLUMN_SPLIT时忽略COLUMN_ORDER

如何通过匹配R中所有可能的组合来从宽到长旋转多个列?

如何将一列中的值拆分到R中各自的列中

如何将一个方阵分解成没有循环的立方体

在ggplot2上从多个数据框创建复杂的自定义图形

如何调整一个facet_work()面板内的框图和移动标签之间的水平宽度?

使用同一行中的前一个值填充R矩阵中的缺失值