【问题标题】:Using for loop for statistics by data frame column in R使用for循环按R中的数据框列进行统计
【发布时间】:2016-10-01 13:51:40
【问题描述】:

我一直在尝试创建一个循环,该循环采用我想要使用的列名的向量,然后对确定样本组的列执行统计测试循环。这是它现在的样子。

sink('df_statistics.txt')

df <- `df.tsv`

columns <- c("column1" , "column2" , "column3" , "column4")

for (x in columns) {
    wilcox.test(formula = x ~ Group, data = df)
}

sink()

当我运行它时,我得到了这个错误:

model.frame.default 中的错误(公式 = 数据 ~ 组,数据 = df):
可变长度不同(为“组”找到)

我的组由数字 1 和 2 决定。 我也尝试将它们命名为控制和实验,但我不断收到与上述相同的错误。有什么建议?

【问题讨论】:

  • 试试for (x in columns) {x1 &lt;- df[c('Group', x)];;wilcox.test(x=x1[,1], y = x1[,2]) } 或者lapply(df[columns], function(x) wilcox.test(x~df$Group))

标签: r for-loop statistics


【解决方案1】:

您无法以编程方式访问具有原始符号的列。使用 [[ ]] 表示法选择带有变量的所需列。
试试:

columns <- c("column1" , "column2" , "column3" , "column4")

for (x in columns) {
    wilcox.test(formula = df[[x]] ~ df$Group)
}

【讨论】:

    【解决方案2】:

    我们可以使用lapply

    lapply(df[columns], function(x) wilcox.test(x~df$Group))
    

    数据

    columns <- c("column1" , "column2")
    set.seed(24)
    df <- data.frame(Group = rep(1:2, each=5), column1 = rnorm(10), column2 = rnorm(10))
    

    【讨论】:

    • 我用我拥有的变量替换了变量,但出现了这个错误。 [.data.frame(df, columns) 中的错误:选择了未定义的列。 @akrun
    • @user3930423 这意味着这些列是数据集中的列。我展示了一个可重现的有效示例。
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多