【问题标题】:R: Generating a data frame to hold an unknown number of elementsR:生成一个数据框来保存未知数量的元素
【发布时间】:2019-07-24 05:54:59
【问题描述】:

我正在估计许多线性模型,其中两个因子变量之间的交互作用来自大量因子变量作为预测变量。因素的级别数可能不同,手动计算级别数非常耗时。从这些模型中,我试图生成一个数据框,其中包含仅用于交互项的每个系数估计的行。 lm 对象中的系数估计值存储在命名向量中,但我将它们存储在 df 中。

目前,我设计了一个函数来为每个模型生成一个包含这些术语的数据框。我可以这样做,保存结果,然后最终读入并附加/加入数据帧,但我知道这非常缓慢且效率低下。

有没有人知道如何计算模型中的交互项的数量,然后将结果存储在我生成的数据框中以适应结果的数量?

下面是一个最小的工作示例,我在生成数据帧后打印它们。我也可以救他们。

# Generate fake data
a <- as.factor(sample(0:1, 20, replace = TRUE))
b <- as.factor(sample(c("a","b","c","d","e","f"), 20, replace = TRUE))
c <- as.factor(sample(0:10, 20, replace = TRUE))
d <- as.factor(sample(0:12, 20, replace = TRUE))
y <- rnorm(20)
df <- data.frame(y,a,b,c,d)

# The factor variable names are:
vars <- c("a","b","c", "d")

# Loop through all the factors
for (i in 1:(length(vars) - 1)){
  for (j in (i+1):length(vars)){

    # Generate the right-hand side of the formula using
    # the fact that (x+y+z)^2 expands in the lm() formula
    # to all main and interaction terms for all two-way
    # interactions: (x + y + z + x:y + x:z + z:y)
    rhs <- c(vars[i], vars[j]) %>% 
      paste(., collapse = "+") %>%
      paste0("(", ., ")", "^2")

    # Generate left-hand side
    lhs <- paste0("y", " ~ ")

    # Generate the model formula
    my_mod <- paste0(lhs, rhs) %>% 
      formula()

    # Fit the model, save coefficients
    mod_sum <- lm(my_mod, data = df)
    mod_coef <- mod_sum$coefficients

    # Identify interaction coefficients by the ":"
    # symbol and keep only the interaction terms in a df
    int_coefs_df <- mod_coef %>% 
      names() %>% 
      grep(":",.) %>%
      mod_coef[.] %>%
      data.frame(estimate = .)

    print(int_coefs_df)
  }
}

【问题讨论】:

    标签: r data-manipulation


    【解决方案1】:

    当您想要累积多个数据帧并且无法预先估计您将需要多少数据帧时,您可以使用列表。或者,如果数据框的大小不同。

    results <- list()
    k <- 1
    for (i in vars) {
      for (j in mars) {
        # do calculations
        newresult <- calculation(i, j)
        if (skipsavingresult)
          next
        results[[k]] <- newresult
        k <- k + 1
      }
    }
    all_results <- dplyr::bind_rows(results) ## this is where you concatenate
    

    您应该考虑这种方法,而不是 results &lt;- rbind(results, newresult)(或类似的)的幼稚方法。在后面的例子中,保存结果会花费越来越长的时间,因为 each 迭代 all 中的数据results 和newresult 被复制并保存在一个新的多变的。 R 中的列表更智能;每次你追加一个结果时,它只是从新索引的列表中添加一个有点指针到你的变量,即没有数据复制。

    【讨论】:

    • 我在您的代码中没有看到任何函数定义。用这种行为的最小工作示例提出一个新问题。最好的机会是您无法重现错误,但获得正确的行为,然后您可以在“生产”代码中使用。
    • 我的错误:我忘记了删除代码以使我的 MWE 更小!一切都很好。
    【解决方案2】:

    我遵循了您的代码并设置了一些种子以尝试生成可重现的示例。

    set.seed(1)
    a <- as.factor(sample(0:1, 20, replace = TRUE))
    set.seed(2)
    b <- as.factor(sample(c("a","b","c","d","e","f"), 20, replace = TRUE))
    set.seed(3)
    c <- as.factor(sample(0:10, 20, replace = TRUE))
    set.seed(4)
    d <- as.factor(sample(0:12, 20, replace = TRUE))
    set.seed(5)
    y <- rnorm(20)
    df <- data.frame(y,a,b,c,d)
    

    为了计算总交互次数,可以运行以下代码:

    Levels <- c(length(levels(a)), length(levels(b)),
                length(levels(c)), length(levels(d)))
    TempLevels <- Levels - 1
    Total <- 0
    for(i in 1:length(Levels) - 1){
      Total <- Total + TempLevels[1] * sum(TempLevels[-1])
      TempLevels <- TempLevels[-1]
    }
    

    应该返回 177 个不同的交互。然后,您可以使用它来创建 data.frame 以存储值。不知道这会有多快。

    【讨论】:

    • 我认为它返回 151
    • 不确定你在这里循环的目的是什么。您正在按 i 进行索引,但循环中没有 i。
    • @PaoloLorenzini 我的错。可能是因为我使用了 R 3.6。我尝试使用 R 3.5,它返回 151。
    • @user3614648 在这种情况下,对象“Levels”的长度为 4,我想循环 3 次。但问题是,在每次迭代期间,我想引用第一个元素,因为我在每次迭代后删除了第一个元素。
    猜你喜欢
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多