首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对于R,我希望遍历每一行并为每一行创建相应的chisquare结果。

对于R,我希望遍历每一行并为每一行创建相应的chisquare结果。
EN

Stack Overflow用户
提问于 2021-03-22 17:30:14
回答 1查看 45关注 0票数 1

例如,我有一个数据集

代码语言:javascript
复制
structure(list(`total primary - yes RS` = c(138L, 101L, 86L, 
118L), `total primary - no RS` = c(29L, 39L, 35L, 38L), `total secondary- yes rs` = c(6L, 
15L, 3L, 15L), `total secondary- no rs` = c(0L, 7L, 1L, 2L)), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))

我能够单独运行每一行并获得我想要的信息,例如

代码语言:javascript
复制
Result<-tidy(chisq.test(matrix(unlist(df[1,]), ncol  = 2)))
Result2<-tidy(chisq.test(matrix(unlist(df[2,]), ncol  = 2)))
Result3<-tidy(chisq.test(matrix(unlist(df[3,]), ncol  = 2)))
Result4<-tidy(chisq.test(matrix(unlist(df[4,]), ncol  = 2)))

但是我想在一个循环中运行它,而不必重复相同的代码4行,times.My的目标是这样的东西。

代码语言:javascript
复制
 statistic|p.value|parameter|method
 0.3165439  0.5736921   1     Pearson's Chi-squared test with Yates' continuity correction 
 0.01656976 0.8975764   1     Pearson's Chi-squared test with Yates' continuity correction
 6.698956e-32   1       1     Pearson's Chi-squared test with Yates' continuity correction
 0.7511235  0.3861208   1     Pearson's Chi-squared test with Yates' continuity correction

做了这样的尝试

代码语言:javascript
复制
library(broom)

Results<-for (i in 1:nrow(df)) {
assign(tidy(chisq.test(matrix(unlist(df[1,]), ncol  = 2))))
}

归功于:为先前的帮助而设的

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-22 17:31:34

一个选项是applyMARGIN = 1来循环行。在每一行中,它都是一个vector,因此我们只需要用matrix包装,就可以转换为具有指定dim枚举的matrix,应用chisq.test并使用tidy以tibble格式获取输出。

代码语言:javascript
复制
library(broom)
library(dplyr)
apply(df, 1, function(x) tidy(chisq.test(matrix(x, ncol = 2)))) %>%
     bind_rows

也可以在tidyversepmap中完成。

代码语言:javascript
复制
library(purrr)
pmap_dfr(df, ~ c(...) %>%
             matrix(ncol = 2) %>%
             chisq.test %>%
             tidy)

-output

代码语言:javascript
复制
# A tibble: 4 x 4
#  statistic p.value parameter method                                                      
#      <dbl>   <dbl>     <int> <chr>                                                       
#1  3.17e- 1   0.574         1 Pearson's Chi-squared test with Yates' continuity correction
#2  1.66e- 2   0.898         1 Pearson's Chi-squared test with Yates' continuity correction
#3  6.70e-32   1.00          1 Pearson's Chi-squared test with Yates' continuity correction
#4  7.51e- 1   0.386         1 Pearson's Chi-squared test with Yates' continuity correction
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66750999

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档