【问题标题】:How to loop between columns to calculate the variables如何在列之间循环以计算变量
【发布时间】:2021-02-05 22:21:28
【问题描述】:

下面,假设这是数据的一部分:

df <- tribble(
    ~temp1, ~temp2, ~temp3, ~temp4, ~temp5, ~temp6, ~temp7, ~temp8,
    75, 88, 85, 71, 98, 76, 71, 57,
    80, 51, 84, 72, 59, 81, 70, 64,
    54, 65, 90, 66, 93, 88, 77, 59,
    59, 87, 94, 75, 74, 53, 56, 87,
    52, 55, 64, 77, 50, 64, 83, 87,
)

现在我想创建一个循环来获取结果。在此示例中,temp1 应仅与 temp2 一起使用,temp3 应仅与 temp4 一起使用,temp5 仅与 temp6 一起使用,temp7 与 temp8 一起使用。

假设我想在预期变量(temp1 与 2、temp3 与 temp4、temp5 与 tem6、temp7 与 temp8 之间)之间运行相关性或 t 检验

我还想只获取统计信息,例如只获取 r 的相关值...一个表格会很有帮助。

我已经搜索过似乎我们需要使用地图的功能,但我很难做到。我们可以在 R 中实现吗?

【问题讨论】:

    标签: r loops lapply


    【解决方案1】:

    我们可以使用seq对列进行子集化并使用map2,这样我们就可以得到temp1和temp2、temp3和temp4等之间的相关性

    library(purrr)
    out <- map2_dbl(df[seq(1, ncol(df), 2)], df[seq(2, ncol(df), 2)], ~ cor(.x, .y))
    names(out) <- paste0("Time", seq_along(out))
    

    或与Map 来自base R

    out <- unlist(Map(function(x, y) cor(x, y), df[seq(1, ncol(df), 2)], 
               df[seq(2, ncol(df), 2)]))
    names(out) <- paste0("Time", seq_along(out))
    

    【讨论】:

    • 谢谢,我们如何将结果重命名为 temp1、tem3、temp5、temp7,比如说 Time1、Time2、Time3、Time4。有可能吗?
    • @user330 您可以使用pasteseq_along 来更改向量的名称。更新了帖子
    • @user330 你想要cort.test?
    • @user330 这对我有用map2(df[seq(1, ncol(df), 2)], df[seq(2, ncol(df), 2)], ~ t.test(.x, .y)) 并且t.test 的输出是list。您需要提取相关信息。我从map中删除了_dbl
    【解决方案2】:

    您可以将数据框分成两部分:一个包含 1、3、5、7 列,另一个包含 2、4、6、8 列。 然后你每次取一列并执行cort.testpmap

    library(purrr)
    df %>% 
     split.default(rep_len(1:2, ncol(.))) %>% 
     pmap_dbl(~cor(.x,.y))
    

    【讨论】:

    • 好吧,因为在这种情况下你需要pmap(~t.test(.x,.y))t.test 不返回双精度数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 2021-11-19
    相关资源
    最近更新 更多