【问题标题】:How to calculate the average of the same column (with same name) in 100s different csv files with part of file name in common?如何计算 100s 不同 csv 文件中相同列(具有相同名称)的平均值,其中部分文件名相同?
【发布时间】:2023-01-11 16:15:28
【问题描述】:

我有一堆结构如下的 csv 文件:

df <- data.frame (first_column  = c(3, 2, 6, 7),
                  second_column = c(7, 5, 1, 8))

所有的 csv 文件都有一个名字

"type1_1.csv"
"type1_2.csv"
...
"type2_1.csv"
"type2_2.csv"
...

这些 csv 中的每一个都有 first_columnsecond_column。我想要的是创建一个如下所示的新数据框:

# name        meanofsecond_column
# type1_1     5.25
# ...

我已经开始做的是分别写出每一个:

type1_1 <- read_csv("type1_1.csv")
type1_1mean <- mean(type1_1$second_column)
...
df <- data.frame (name  = c(type1_1, type1_2...),
                  meanofsecondcolumn = c(type1_1mean, type1_2mean...))

然而,由于有超过 100 个 csv 文件,这种方法不是很有效或干净。我怎样才能让它更浓缩?

【问题讨论】:

    标签: r dataframe csv import mean


    【解决方案1】:
    # path where your csv files are (here current working directory)
    CSV_FOLDER <- "."
    
    # list all csv files in given directory
    # second parameter is a regex meaning ends with .csv
    # third parameter make function return file names with path
    csv_files <- list.files(CSV_FOLDER, "\.csv$", full.names=TRUE)
    
    # apply given function on each file and collect results in a list
    res <- lapply(csv_files, function(csv_file) {
      # read current file
      tmp <- read.csv(csv_file)
    
      # build a data.frame from filename (without path) and mean of second column
      return(data.frame(
        name = basename(csv_file),
        meanofsecondcolumn = mean(tmp$second_column)
      ))
    })
    
    # rbind all single line data.frames in a single data.frame
    res <- do.call("rbind", res)
    

    【讨论】:

    • 感谢您的彻底回复Error in do.call(rbind(res)) : argument "args" is missing, with no default 我收到此错误。
    • 我的错,已解决 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多