问题
Afternoon (or morning, evening)
I am trying to merge several .csv
files that have a similar layout, they have a class in one column (character
) and an abundance (num
) in another.
When imported as a data.frame
example would be:
print(one[1:5,])
X Class Abundance_inds
1 1 Chaetognath 2
2 2 Copepod_Calanoid_Acartia_spp 9
3 3 Copepod_Calanoid_Centropages_spp 4
4 4 Copepod_Calanoid_Temora_spp 1
5 5 Copepod_Calanoid_Unknown 55
The class column (number of rows and order) changes every csv based on what was found and I want to bind several (30+) csvs based on the class column, I had the following (which I am sure was working a while ago.....):
DensityFiles <- list.files(CSVdirectory,
pattern = '.csv',
full.names = T)
Combined <- rbindlist(
lapply(
DensityFiles,
fread),
fill = TRUE,
use.names = TRUE)
This produces the following:
str(Combined)
Classes ‘data.table’ and 'data.frame': 461 obs. of 3 variables:
not quite what I was after! I am looking for the following:
> print(example)
X Class CSV.NAME CSV.NAME.1
1 1 Bivalve_Larvae 1 3
2 2 Bryozoa_Larvae 4 6
3 3 Chaetognath NA 7
4 4 Cnidaria 1 8
5 5 Copepod_Calanoid_Acartia_spp 22 NA
6 6 Copepod_Calanoid_Calanus_spp 24 4
7 7 Copepod_Calanoid_Candacia_sp 5 3
8 8 Copepod_Calanoid_Centropages_spp 41 2
9 9 Copepod_Calanoid_Temora_spp 39 8
10 10 Copepod_Calanoid_Unknown 458 NA
11 11 Copepod_Cyclopoid_Corycaeus_spp 46 NA
12 12 Copepod_Cyclopoid_Oithona_spp NA 4
13 13 Copepod_Cyclopoid_Oncaea_spp NA 7
14 14 Copepod_Harpacticoid 36 NA
15 15 Copepod_Nauplii 12 9
I can get the CSV name into the column header using idcol = "origin"
when using
data.table
libary rbindlist
. but not sure if this works for all solutions.
I have had a good hunt around but most examples seem to be dealing with a consistent number of rows,
any help would be greatly appreciated!
Jim
回答1:
You can use readr
and bind_rows
library(dplyr)
library(readr)
df <- do.call(bind_rows, lapply(DensityFiles,read_csv))
来源:https://stackoverflow.com/questions/55024669/merge-csvs-based-on-common-column-but-of-inconsistent-length