在 R 中,apply() 在应用于多个列时会抛出很多警告。这些警告有多重要?

问题描述 投票:0回答:1

请考虑以下 MWE。我正在练习一种技术,我将几个线性模型的结果绑定到一个数据框(tibble),然后应用自定义函数(这里,对于这个 MWE 进行了粗略的简化)来进行一些舍入/其他修改,然后最后将 tibble 传递给灵活的。

library(dplyr)
library(flextable)

# Load example data
data("mtcars")

# Run linear models
model1 <- lm(mpg ~ hp, data = mtcars)
model2 <- lm(mpg ~ hp + wt, data = mtcars)

# Extract the statistics
coef_table1 <- summary(model1)$coefficients["hp", c("Estimate", "Std. Error", "Pr(>|t|)")]
coef_table2 <- summary(model2)$coefficients["hp", c("Estimate", "Std. Error", "Pr(>|t|)")]

# Combine results to matrix; then, convert to tibble
results <- rbind(coef_table1, coef_table2) %>% as_tibble()

# Name the models
results <- results %>% mutate(Model = c("Model1", "Model2")) %>% relocate(Model, .before = Estimate)

# Display results
results %>% flextable()

# Create custom round function for statistics other that p-values
custom_round <- function(x) {
  case_when(
    x >= 0 && x < 0.01 ~ "<.01",
    TRUE ~ paste0(format(round(x, 2), nsmall = 2))
  )
}

# Create custom function for p-values
custom_round_p <- function(x) {
  case_when(
    x >= 0 && x < 0.05 ~ "<.05",
    TRUE ~ paste0(format(round(x, 2), nsmall = 2))
  )
}

# Apply the custom round functions to different sections of
# the results tibble with apply()
results_rounded <- bind_cols(results[1],
                      apply(results[2:3], 2, custom_round),
                      apply(results[4], 2, custom_round_p))

#> Warning in x >= 0 && x < 0.01: 'length(x) = 2 > 1' in coercion to 'logical(1)'

#> Warning in x >= 0 && x < 0.01: 'length(x) = 2 > 1' in coercion to 'logical(1)'

#> Warning in x >= 0 && x < 0.01: 'length(x) = 2 > 1' in coercion to 'logical(1)'
#> Warning in x >= 0 && x < 0.05: 'length(x) = 2 > 1' in coercion to 'logical(1)'

#> Warning in x >= 0 && x < 0.05: 'length(x) = 2 > 1' in coercion to 'logical(1)'

# Display rounded results
results_rounded %>% flextable()

创建于 2023 年 4 月 28 日(可弯曲部分除外)与 reprex v2.0.2

代码工作正常,但

apply()
抛出上述警告。这些与此 MWE 中描述的用法有多少相关性?

r apply
1个回答
0
投票

相关重复问题:

通过将

&&
更改为
&
来修复您的代码。

custom_round <- function(x) {
  case_when(
    x >= 0 & x < 0.01 ~ "<.01",
    TRUE ~ paste0(format(round(x, 2), nsmall = 2))
  )
}

# Create custom function for p-values
custom_round_p <- function(x) {
  case_when(
    x >= 0 & x < 0.05 ~ "<.05",
    TRUE ~ paste0(format(round(x, 2), nsmall = 2))
  )
}

我还建议使用

mutate
/
across
而不是将
apply
绑定在一起。

results %>%
  mutate(
    across(Estimate:`Std. Error`, custom_round),
    `Pr(>|t|)` = custom_round_p(`Pr(>|t|)`)
  )
# # A tibble: 2 × 4
#   Model  Estimate `Std. Error` `Pr(>|t|)`
#   <chr>  <chr>    <chr>        <chr>     
# 1 Model1 -0.07    0.01         <.05      
# 2 Model2 -0.03    <.01         <.05      
© www.soinside.com 2019 - 2024. All rights reserved.