【问题标题】:How do I perform a function on multiple rows of data which are factored by the column they are in R?如何对多行数据执行函数,这些数据由它们在 R 中的列分解?
【发布时间】:2012-10-16 13:14:57
【问题描述】:

我在一个文件中有一个表,其中包含我使用 R 读入的许多行

data <-read.table("path/to/data.txt",header=TRUE, sep="\t",row.names=1)
            A1    A2    A3    B1    B2    B3
    Row1    1      3    2     3     2     6    
    Row2    3      2    1     3     6     7
    ...

然后我使用

将其读入框架
df <-data.frame(data)

我想执行一个函数()来比较每行的 A 样本和 B 样本,

function(A,B)

但我不确定如何从数据框中为每一行仅指定 A 和 B - 有没有办法一次性为整个数据表执行此操作?我是否必须将数据读入一个框架,或者我可以直接从最初的 read.table 数据中工作吗?

【问题讨论】:

  • 到目前为止你尝试过什么? “将 A 样本与 B 样本进行比较”是什么意思?您的预期结果是什么?
  • 具体来说,我想在每一行上执行 wilcoxon.test 函数,但我不确定如何指定条目,语法是 wilcox.test(sampA,sampB) 我想在每个行上执行它表格的行
  • 对于 Row1,sampA 将是第一行 (1,3,2) 中 A1、A2、A3 下的三个条目,sampB 将是第一行 B1、B2、B3 下的三个条目行 (3,2,6),但我想对文件中的每一行都执行此操作
  • 我是 R 新手,我到处找,但我无法找出如何指定特定的列和行,我知道调用我可以使用的第一行data[1,] 但我找不到仅调用前 3 列或后 3 列的语法,我也尝试使用因子 factor(c(1,1,1,2,2,2)) 但我不知道如何指定 1 和 2

标签: arrays r function data.table


【解决方案1】:

试试这个:

set.seed(001) # Generating some data
DF <- data.frame(A1=sample(1:9, 10, T),
                 A2=sample(1:9, 10, T),
                 A3=sample(1:9, 10, T),
                 B1=sample(1:9, 10, T),
                 B2=sample(1:9, 10, T),
                 B3=sample(1:9, 10, T))


sampA <- DF[,grep('A', names(DF))]  # Sample with columns A
sampB <- DF[,grep('B', names(DF))]  # Sample with columns B


lapply(1:nrow(DF), function(i){
  wilcox.test(as.numeric(sampA[i,]), as.numeric(sampB[i,]), exact=FALSE )
})  # Performing the test

结果如下:

[[1]]

    Wilcoxon rank sum test with continuity correction

data:  as.numeric(sampA[i, ]) and as.numeric(sampB[i, ]) 
W = 3, p-value = 0.6579
alternative hypothesis: true location shift is not equal to 0 


[[2]]

    Wilcoxon rank sum test with continuity correction

data:  as.numeric(sampA[i, ]) and as.numeric(sampB[i, ]) 
W = 0, p-value = 0.0722
alternative hypothesis: true location shift is not equal to 0 


[[3]]

    Wilcoxon rank sum test with continuity correction

data:  as.numeric(sampA[i, ]) and as.numeric(sampB[i, ]) 
W = 6, p-value = 0.6579
alternative hypothesis: true location shift is not equal to 0 

我只显示了前 3 个结果,完整的列表长度为 10,因为 DF 有 10 行。

【讨论】:

  • 感谢@Jilber - 在您的示例中,每个 htest 输出似乎都将自己保存到 [[1]]、[[2]] 和 [[3]] 的不同条目中。我想将输出保存到一个文本文件中,并且想知道我将如何做到这一点,因为我不能为此使用 write.table。是否可以从 htest 结果中提取 W 和 p 值并将其粘贴到我可以保存到文本文件的框架中?
  • 嗨 - 我刚刚解决并使用了data.frame(unlist(output))。再次感谢!
  • @user1637359,很高兴有用。您也可以为答案投票。
猜你喜欢
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 2023-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多