r - 在 r 中读取 csv 时将列名称添加到数据框

标签 r csv dataframe multiple-columns read.csv

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

Error in match.names(clabs, names(xi)) : names do not match previous names.

因此,出于这个原因,我想将列名称附加到这些 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")

有什么建议吗?

最佳答案

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


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

关于r - 在 r 中读取 csv 时将列名称添加到数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47344121/

相关文章:

r - 如何根据关联条件在 dplyr 中进行过滤

r - 将具有最大值的列的索引添加为新列

使用 r 将栅格转为表格

Python DataFrame - 删除列值属于值列表的行

python-3.x - Pandas 窗口聚合两个排序表

r - 以批处理模式执行 R 代码时的用户输入

sorting - 在 Pentaho 中对 200-3 亿条记录进行排序的最佳方法?

php - 如何在不覆盖的情况下向 CSV 文件添加行

Excel - 将以 Z 结尾的 ISO8601 日期转换为适合输入类型为 'timestamp with time zone' 的 Postgres 字段的格式

python - 计算数据框中字符串的出现次数