将多个.csv文件导入到具有不同名称的R中

问题描述 投票:0回答:1

我有一个工作目录,包含37个Locations.csv和37个Behavior.csv

看下面有一些文件与111868-Behavior.csv111868-Behavior 2.csv具有相同的编号,因此也有Locations.csv

#here some of the csv in the work directory

dir()
  [1] "111868-Behavior 2.csv"            "111868-Behavior.csv"             
  [3] "111868-Locations 2.csv"           "111868-Locations.csv"            
  [5] "111869-Behavior.csv"              "111869-Locations.csv"            
  [7] "111870-Behavior 2.csv"            "111870-Behavior.csv"             
  [9] "111870-Locations 2.csv"           "111870-Locations.csv"            
 [11] "112696-Behavior 2.csv"            "112696-Behavior.csv"             
 [13] "112696-Locations 2.csv"           "112696-Locations.csv"    

我无法更改文件名。

我想导入所有36个位置和36个行为,但是当我尝试这个时

#Create list of all behaviors
bhv <- list.files(pattern="*-Behavior.csv")
bhv2 <- list.files(pattern="*-Behavior 2.csv")

#Throw them altogether
bhv_csv = ldply(bhv, read_csv)
bhv_csv2 = ldply(bhv2, read_csv)

#Join bhv_csv and bhv_csv2
b<-rbind(bhv_csv,bhv_csv2)

#Create list of all locations
loc <- list.files(pattern="*-Locations.csv")
loc2 <- list.files(pattern="*-Locations 2.csv")

#Throw them altogether
loc_csv = ldply(loc, read_csv)
loc_csv2 = ldply(loc2, read_csv)

#Join loc_csv and loc_csv2
l<-rbind(loc_csv,loc_csv2)

显示我只有28,而不是像我预期的36

length(unique(b$Ptt))
[1] 28

length(unique(l$Ptt))
[1] 28

这个数字28,大约是没有Behaviors.csvLocations.csv的所有Behaviors 2.csvLocations 2.csv(数字“2”的每一个共8个)

我想以一种显示36个行为和位置的方式导入所有文件行为和所有位置。我怎样才能做到这一点?

r csv import filenames
1个回答
0
投票

您可以使用purrr::map来简化您的一些代码:

library("tidyverse")
library("readr")

# Create two small csv files
write_lines("a,b\n1,2\n3,4", "file1.csv")
write_lines("a,c\n5,6\n7,8", "file2.csv")

list.files(pattern = "*.csv") %>%
  # `map` will cycle through the files and read each one
  map(read_csv) %>%
  # and then we can bind them all together
  bind_rows()
#> Parsed with column specification:
#> cols(
#>   a = col_double(),
#>   b = col_double()
#> )
#> Parsed with column specification:
#> cols(
#>   a = col_double(),
#>   c = col_double()
#> )
#> # A tibble: 4 x 3
#>       a     b     c
#>   <dbl> <dbl> <dbl>
#> 1     1     2    NA
#> 2     3     4    NA
#> 3     5    NA     6
#> 4     7    NA     8

reprex package创建于2019-03-28(v0.2.1)

© www.soinside.com 2019 - 2024. All rights reserved.