我想在 R 中对我的数据执行两个样本的 t 检验。 给定两个高维数据帧,我需要以某种方式遍历所有行的匹配列( header 中的 String colnames()),并对每一列对执行测试 - 分别来自 df1 和 df2。问题在于数据框中的列顺序不正确,即 df1 中的 col1 与 df2 中的 col1 不匹配,并且 df2 具有 df1 中不存在的其他列。我从未将 R 用于此类任务,我想知道是否有一种快速方便的解决方案可以在数据框中找到匹配的列对以进行 t 检验。
我考虑过 for 循环,但我认为这对于大型数据帧来说效率非常低。
提前感谢您的帮助。
*已编辑--------两个小示例数据帧,df1 和 df2---------------------------- -----
****df1****
"Row\Column" "A2" "A1" "A4" "A3"
"id_1" 10 20 0 40
"id_2" 5 15 25 35
"id_3" 8 0 12 16
"id_4" 17 25 0 40
****df2****
"Row\Column" "A3" "A8" "A5" "A6" "A1" "A7" "A4" "A2"
"id_1" 0 2 0 4 0 1 2 3
"id_2" 1 5 8 3 4 5 6 7
"id_3" 2 10 6 9 8 9 10 11
"id_4" 7 2 10 2 55 0 0 0
"id_5" 0 1 0 0 9 1 3 4
"id_6" 8 0 1 2 7 2 3 0
匹配的列只是 df1 中的列名与 df2 中的列名相匹配。 例如 df1 和 df2 中的两个匹配列是 e。 G。 “A1”和“A1”、“A2”和“A2”……你明白了……
最佳答案
mapply
是您正在寻找的功能。
如果您的 data.frame
的列匹配,您可以简单地使用
mapply(t.test, df1, df2)
但是,由于它们不存在,因此您需要以某种方式确定 df1
的哪一列与 df2
的哪一列对应。幸运的是,R
中的索引选项很聪明,如果您输入列名的向量(集合),您将按给定的顺序取回这些列。这让生活变得轻松。
# find the matching names
## this will give you those names in df1 that are also in df2
## and *only* such names (ie, strict intersect)
matchingNames <- names(df1)[names(df1) %in% names(df2)]
注意 matchingNames
有一些顺序
现在看看当您使用 matchingNames
向量作为每个 df1 和 df2 的列的索引时会发生什么(另请注意列顺序)
df1[, matchingNames]
df2[, matchingNames]
matchingNames
因此,我们现在有两个具有正确匹配列的 data.frames,我们可以使用它们来映射
。
## mapply will apply a function to each data.frame, one pair of columns at a time
## The first argument to `mapply` is your function, in this example, `t.test`
## The second and third arguments are the data.frames (or lists) to simultaneously iterate over
mapply(t.test, df1[, matchingNames], df2[, matchingNames])
关于R- 在两个数据框中找到匹配的列以进行 t 检验统计(R 初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15865112/