【问题标题】:Looping in R: Using Index to Bracket SubsetR中的循环:使用索引括号子集
【发布时间】:2020-09-06 04:12:53
【问题描述】:

我正在尝试在 R 中编写一个 for 循环,使用索引值来对数据进行子集化,但我得到了我的括号意外的错误。当我从代码主体中删除它们时,我收到一个错误,即找不到我正在创建的对象(是的!不应该找到它......循环应该创建它)。我熟悉循环,但在 R 中编写循环的经验较少。要明确的是,我不明白何时使用单括号 [i] 或双括号 [[i]]。我只是希望我的循环成功运行并生成 24 次效果大小计算。

我尝试了许多 [i]、[[i]] 和 i 的组合。我也更改了指标上的变量类型,但无济于事。

感谢您的帮助!

我目前的代码如下:

数据集示例:

structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 
2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3), id = c("Person1", "Person1", 
"Person1", "Person1", "Person1", "Person1", "Person1", "Person1", 
"Person2", "Person2", "Person2", "Person2", "Person2", "Person2", 
"Person2", "Person2", "Person3", "Person3", "Person3", "Person3", 
"Person3", "Person3", "Person3", "Person3"), year = c(2, 2, 2, 
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
), indicator = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 
4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L), score = c(3.5, 
3.5, 2, 3, 3.5, 4, 3, 4, 2.25, 2.5, 1.75, 1.5, 2, 2.75, 2, 2.75, 
1.75, 2, 1.75, 2, 2, 2.5, 2, 2.5)), class = c("tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -24L))

当前形式的代码:

library(effsize)

for(i in 1:8){
a.1.1.[i]<-cohen.d((df[df$Group==1 & df$indicator==[i],]$score), (df[df$Group==2 & df$indicator==[i],]$score),pooled=T, hedges.correction = T, na.rm=T)

a.1.2.[i]<-cohen.d((df[df$Group==2 & df$indicator==[i],]$score), (df[df$Group==3 & df$indicator==[i],]$score),pooled=T, hedges.correction = T, na.rm=T)

a.1.3.[i]<-cohen.d((df[df$Group==1 & df$indicator==[i],]$score), (df[df$Group==3 & df$indicator==[i],]$score),pooled=T, hedges.correction = T, na.rm=T)
}

【问题讨论】:

    标签: r for-loop subset


    【解决方案1】:

    将数据存储在列表中:

    a.1.1 <- vector('list', 8)
    a.1.2 <- vector('list', 8)
    a.1.3 <- vector('list', 8)
    
    for(i in 1:8) {
      a.1.1[[i]] <- cohen.d((df$score[df$Group==1 & df$indicator==i]), 
                            (df$score[df$Group==2 & df$indicator==i]),
                             pooled=T, hedges.correction = T, na.rm=T)
      
      a.1.2[[i]]<-cohen.d((df$score[df$Group==2 & df$indicator==i]), 
                         (df$score[df$Group==3 & df$indicator==i]),
                          pooled=T, hedges.correction = T, na.rm=T)
      
      a.1.3[[i]] <- cohen.d((df$score[df$Group==1 & df$indicator==i]), 
                          (df$score[df$Group==3 & df$indicator==i]),
                           pooled=T, hedges.correction = T, na.rm=T)
    }
    

    【讨论】:

    • 谢谢!您能否分享一下何时使用单、双、无括号?
    • 这取决于你想做什么。如果您将数据存储在列表中(如本例中),则需要使用双括号。要将数据存储在向量中,您可以使用单括号。提取数据也是如此。有关它们之间的详细区别,请参阅此帖子stackoverflow.com/questions/1169456/…
    猜你喜欢
    • 2015-08-14
    • 2021-10-13
    • 1970-01-01
    • 2015-05-28
    • 2017-12-29
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    相关资源
    最近更新 更多