gpt4 book ai didi

r - .subset2(x, i, exact = exact) 错误 : subscript out of bounds in R

转载 作者:行者123 更新时间:2023-12-05 04:57:08 28 4
gpt4 key购买 nike

我正在尝试循环数据框中的特定数字列,目标是使用“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

关于r - .subset2(x, i, exact = exact) 错误 : subscript out of bounds in R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64612754/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com