首页 > 解决方案 > 在参与者的 R 中创建一个循环;每个参与者创建 1 个箱线图 .tiff

问题描述

亲爱的 Stack Overflow 社区,

我想使用不同的 .csv 文件(每个参与者 1 个)执行 4 个参与者的循环。对于每个主题,我想生成一个条形图,在 x 轴上依赖“性别(男性,女性)”,在 y 轴上依赖“正确答案的比例”)。

下面显示了每个 .csv 文件在打开时的显示方式:我想为因子 c("observernumber","trial","numstim","memo","sex","corResp","curresp", “成功”)

1   1   284 high    female  a   a   1
2   2   190 low     male    l   l   1
3   3   224 low     male    l   l   1
4   4   218 high    male    l   l   1
5   5   137 high    male    l   l   1
6   6   45  high    female  a   a   1
7   7   87  high    female  a   a   1
8   8   249 high    female  a   a   1
9   9   27  low     male    l   l   1
10  10  53  low     male    l   l   1
11  11  92  low     female  a   a   1
12  12  283 low     male    l   l   1

我首先为每个参与者提供 .csv 名称:

obsNames = c("1_gender","2_gender","3_gender","4_gender")
nsubj <- length(obsNames)

我预先分配了一个读取 obsNames 的矩阵:

allData = c() 
for (i in 1:obsNames) { 
  dat = read.csv(sprintf("%s_gender.csv", obsNames[i]), header = FALSE, sep = ";") 
  obsIndex = rep(i,nrow(dat)) 
  allData = rbind(allData, cbind(obsIndex,dat)) 
}

我列出了我拥有的所有因素:

names(allData) = c("subj", "trial", "sex", "success") 

我想为 4 个当前主题中的每一个绘制一个 .tiff 文件,该文件必须显示 a)b)c):

a) 当前观察者的名字作为title

paste(obsNames[curSubj], ".tiff", sep = "")

b)x轴上的“性别(男性,女性)”因素

"sex"

c) 在 y 轴上使用“正确答案的比例”因子

"success"

我想为每个参与者制作一个箱线图,我应该如何完成这个脚本?如何命名 x 和 y 值?:

for(curSubj in 1:nsubj){
  tiff(file = paste(obsNames[curSubj], ".tiff", sep = "")) 
  barCenters = barplot(
    main = paste(obsNames[curSubj],".tiff",sep = ""),
    yaxt = "n",
    ylab = "Proportion Correct",
    xlab = "Gender"
  ) 
  mgp.axis(labels = c("Female","Male")) 
  dev.off() 
}

使用有错误???

curSubj

标签: rloopsboxplot

解决方案


下面创建一个 TIFF 文件,其中每个 CSV 文件的名称与模式匹配一​​个条形图"gender.csv"
它使用ggplot2图形。

首先,读入文件。

csv_files <- list.files(pattern = "gender\\.csv")
df_list <- lapply(csv_files, read.csv)
obsNames <- sub("\\.csv", "", csv_files)
df_list <- lapply(seq_along(df_list), function(i){
  Y <- cbind.data.frame(obsIndex = obsNames[i], df_list[[i]])
})

现在是条形图,保存在 TIFF 文件中。

library(ggplot2)
library(scales)

for(i in seq_along(df_list)){
  g <- ggplot(df_list[[i]], aes(x = sex)) +
    geom_bar(aes(y = (..count..)/sum(..count..)), 
             stat = "count", position = "dodge") +
    scale_y_continuous(labels = percent) +
    ylab(label = "Proportion of correct answer") +
    ggtitle(obsNames[i])

  outfile <- paste0(obsNames[i], ".tiff")
  tiff(filename = outfile)
  print(g)
  dev.off()
}

数据创建代码。

以下代码在您的工作目录中创建 4 个 csv 文件,并在问题中发布了表的结构。

f <- function(i, n){
  sex <- sample(c("male", "female"), n, TRUE)
  success <- rbinom(n, 1, prob = 0.5)
  df <- data.frame(trial = seq_len(n), sex, success)
  write.csv(df, paste0(i, "_gender.csv"), quote = FALSE, row.names = FALSE)
}

set.seed(1234)
n <- sample(20:50, 4)
lapply(1:4, function(i) f(i, n = n[i]))

推荐阅读