【问题标题】:Adding column names to dataframe while reading a csv in r在读取 r 中的 csv 时将列名添加到数据框
【发布时间】:2017-11-17 05:54:07
【问题描述】:

我的目录中有多个没有列名的 .csv 文件。因此,在没有标题的情况下阅读它们会出现错误

match.names(clabs, names(xi)) 中的错误: 名称与以前的名称不匹配。

因此,出于这个原因,我想将列名附加到这些 csv 文件中,并将它们全部组合到一个数据帧中,但是在读取它们时我无法将列名添加到这些多个 csv 文件中。文件名如 test_abc.csvtest_pqr.csvtest_xyz.csv 等。 这是我尝试过的

temp = list.files(pattern="*.csv")
read_csv_filename <- function(filename){
  ret <- read.csv(filename,header = F)
  ret$city <- gsub(".*[_]([^.]+)[.].*", "\\1", filename) 
  ret
}

df_all <- do.call(rbind,lapply(temp,read_csv_filename))

如何在阅读时将标题添加到每个文件?

这是我想在阅读时添加的名称

colnames = c("Age","Gender","height","weight")

有什么建议吗?

【问题讨论】:

  • 可能是read.csv(..., col.names = c("Age","Gender","height","weight"))?还是我把你的问题弄错了?

标签: r csv dataframe multiple-columns read.csv


【解决方案1】:

使用tidyverse 包,您可以使用purrr::map_dfr 函数很好地做到这一点,该函数迭代列表,对每次返回数据帧的每个元素执行一些函数,并将所有这些数据帧绑定在一起。


library(readr)
library(purrr)
library(dplyr) # only used in example set up

# Setting up some example csv files to work with

mtcars_slim <- select(mtcars, 1:3)

write_csv(slice(mtcars_slim, 1:4), "mtcars_1.csv", col_names = FALSE)
write_csv(slice(mtcars_slim, 5:10), "mtcars_2.csv", col_names = FALSE)
write_csv(slice(mtcars_slim, 11:1), "mtcars_3.csv", col_names = FALSE)


# get file paths, read them all, and row-bind them all

dir(pattern = "mtcars_\\d+\\.csv") %>% 
  map_dfr(read_csv, col_names = c("mpg", "cyl", "disp"))

#> Parsed with column specification:
#> cols(
#>   mpg = col_double(),
#>   cyl = col_integer(),
#>   disp = col_integer()
#> )

#> # A tibble: 21 x 3
#>      mpg   cyl  disp
#>    <dbl> <int> <dbl>
#>  1  21.0     6 160.0
#>  2  21.0     6 160.0
#>  3  22.8     4 108.0
#>  4  21.4     6 258.0
#>  5  18.7     8 360.0
#>  6  18.1     6 225.0
#>  7  14.3     8 360.0
#>  8  24.4     4 146.7
#>  9  22.8     4 140.8
#> 10  19.2     6 167.6
#> # ... with 11 more rows

【讨论】:

  • 我真的很喜欢tidyverse 并且自己也使用它。但是,如果他显然不使用任何一个,为什么只为这个任务加载 3 个包呢?
【解决方案2】:

您可以像这样将列名放在循环本身中

temp = list.files(pattern="*.csv")
read_csv_filename <- function(filename){
  ret <- read.csv(filename,header = F)
  ret$city <- gsub(".*[_]([^.]+)[.].*", "\\1", filename) 
  colnames(ret) <- c("Age","Gender","height","weight","city")

  ret
}

df_all <- do.call(rbind,lapply(temp,read_csv_filename))

【讨论】:

  • read.csv 如果您设置了col.names = c("Age","Gender","height","weight"),则已经有此选项,因此不需要此附加行。而且,如果真的想使用colnames(),您至少应该在添加另一列之前这样做。
猜你喜欢
  • 2019-01-28
  • 2018-04-17
  • 2017-07-25
  • 1970-01-01
  • 2019-10-31
  • 2014-12-28
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多