【问题标题】:Import multiple files and then output the calculation into one file导入多个文件,然后将计算输出到一个文件中
【发布时间】:2020-11-03 20:09:56
【问题描述】:

我有多个名为“sub block#”的 .csv 文件:

01 块1 01块2 01块3 02块1 02块2 02块3

我愿意

  1. 获取按“提示”分组的每个参与者的平均值(我当前的代码尝试获取每个文件的平均值,但不是每个主题)
  2. 将输出保存到一个 .csv 文件
files <- list.files(path="C:/Users/", pattern="*.csv", full.names=TRUE, 
    recursive=FALSE)
            for (file in files ){
              data<-read.csv(file)
              summarize.stat<-
                data%>% 
              group_by(Cue) %>%  # grouping stats
              drop_na() %>%
              summarize(count=n(),
                        mean.RT= mean(RT))
              write.csv(summarize.stat, paste("C:/Users/",'RTcue,csv',sep = ""), 
    row.names = FALSE, quote = FALSE)
         }

这是控制台中显示的内容 summarise() 取消分组输出(用 .groups 参数覆盖) summarise() 取消分组输出(用 .groups 参数覆盖) summarise() 取消分组输出(用 .groups 参数覆盖) summarise() 取消分组输出(用 .groups 参数覆盖) summarise() 取消分组输出(用 .groups 参数覆盖) summarise() 取消分组输出(用 .groups 参数覆盖)

** 错误:summarise() 输入 mean.RT 有问题。 x 在为函数“mean”选择方法时评估参数“x”时出错:找不到对象“RT”** i 输入mean.RTmean(RT)。 i 第 1 组出现错误:Cue = "Center"。

所以我的问题是: 1.如何修复错误? 2.如何得到每个科目的平均值?

感谢您的任何建议!我已经为此苦苦挣扎了一段时间。

【问题讨论】:

  • 你在数据集中有RT 列吗?
  • 是的! RT 在数据集中。我检查了代码是否适用于一个文件
  • 可能至少一个或多个文件的列名不存在

标签: r tidyverse


【解决方案1】:

有多种方法可以解决此问题。一种选择是使用带有if 的条件逻辑来检查读取数据中的列existssummarise 是否存在

library(dplyr)
library(purrr)
library(readr)
library(stringr)
nm1 <- tools::file_path_sans_ext(basename(files))
imap_dfr(setNames(files, nm1), ~ {
            dat <- read_csv(.x) 
            if(exists('RT', where = dat)) {
                   dat %>%
                     group_by(Cue) %>%
                     summarise(Count = n(), 
                        mean.RT= mean(RT, na.rm = TRUE), .groups = 'drop')  %>%
             mutate(filename = .y)
            
      
               } else tibble(Cue = first(dat$Cue),
         mean.RT = NA_real_, filename = .y)
               }) %>%

    write_csv(path  =  file.path("C:/Users/", "RTcue.csv"))

或者另一个选项是tryCatch

【讨论】:

  • 你说的太对了!一个文件没有。现在代码运行但没有生成输出“RTcue.csv”
  • @Sophy 对不起,我会更新的。我注意到的一件事是所有输出的文件名都是相同的。这不会覆盖输出吗?
  • 在控制台中显示“summarise() ungrouping output (override with .groups argument)”。每个文件的输出都在控制台中,但丢失了原始文件名。我希望输出到一个带有原始文件名的 .csv。谢谢!
  • @Sophy 不要担心那个警告。这只是一个友好的警告。您可以使用.groups = 'drop'。请查看here
  • @Sophy 抱歉,, 丢失了。现在可以测试了吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-18
  • 2019-12-09
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
  • 2021-05-02
相关资源
最近更新 更多