.subset2(x, i, exact = exact) 中的错误:R 中的下标越界

Error in .subset2(x, i, exact = exact) : subscript out of bounds in R

我正在尝试循环数据框中的特定数字列,目标是 使用“cor.test”函数提取相关性和 p 值。

相关性在于计算线性关系 一个分类变量由针对每个特定数字列的 0 和 1 值组成。

到目前为止,这是我的代码:

## data ##
names <- c("John", "Greg", "Maria", "Josh", "Emma")
categorical_column <- sample(0:1, 5, replace = TRUE)
numeric_column_1  <- sample(1:30, 5, replace = TRUE)
numeric_column_2 <- sample(1:40, 5, replace = TRUE)

sampled_df <- data.frame(names, categorical_column, numeric_column_1,
                         numeric_column_2)


## specific columns ##

numerical_columns <- c("numeric_column_1", "numeric_column_2")


## for-loop task ##

for(i in seq_along(numerical_columns)){
      
       correlation_num_df <- structure(list(
                         
       variable <- numerical_columns,
                        
       correlation <- cor.test(sampled_df[numerical_columns[i]][[i]],
                       sampled_df[["categorical_column"]])[["estimate"]][["cor"]],
                        
       p_value <- cor.test(sampled_df[numerical_columns[i]][[i]],
                      sampled_df[["categorical_column"]])[["p.value"]]
      ),
    
     class = "data.frame",
     
     nrow = c(NA, -2L))
      
   
}


控制台输出:

Error in .subset2(x, i, exact = exact) : subscript out of bounds

我怎么知道越界的子集?我该如何解决?

我们可以使用 acrosssummarise

library(dplyr)
library(broom)
out <- sampled_df %>% 
   summarise(across(all_of(numerical_columns), 
     ~list(cor.test(., categorical_column) %>% 
             tidy %>% 
             select(estimate, p.value))))

unclass(out) %>%
      bind_rows(.id = 'grp')
# A tibble: 2 x 3
#  grp   estimate p.value
#  <chr>    <dbl>   <dbl>
#1 1        0.408   0.495
#2 2        0.343   0.572