问题
I am reading a variable number of .csv files, all contained in the present working directory, into a list, and would like to rbind the 2nd column of each of these .csv files.
The files in the working directory look like this:
150601_0001.csv
150601_0002.csv
150601_0003.csv
etc.
I have the following code to read them all into a list for any given number of files in the directory: (code comes from here)
myfiles <- dir(pattern = "\\.(csv|CSV)$", full.names = TRUE) # get filenames and paths
myfiles_data <- lapply(myfiles, data.table::fread) # read data from files, quickly
head(myfiles_data[[1]]) # validate file reading
names(myfiles_data) <- myfiles # assign names to list items
This works perfectly fine so far, and I get all the data into a pretty list:
> myfiles_data
$`./150601_0001.csv`
X Y Z
1: 1 67.81 1
2: 2 68.52 1
3: 3 69.66 1
---
250: 250 50.02 1
251: 251 50.58 1
252: 252 51.16 1
$`./150601_0002.csv`
X Y Z
1: 1 70.77 2
2: 2 70.54 2
3: 3 70.47 2
---
250: 250 51.00 2
251: 251 51.17 2
252: 252 51.43 2
$`./150601_0003.csv`
X Y Z
1: 1 68.32 3
2: 2 67.80 3
3: 3 67.33 3
---
250: 250 50.58 3
251: 251 50.68 3
252: 252 50.77 3
Now I want to rbind on the second column of each data set. The following code gives me a list with only the second columns (data was abbreviated for visual purposes):
> lapply(myfiles_data, `[[`, 2)
$`./150601_0001.csv`
[1] 67.81 68.52 69.66 ...
...
[241] ... 52.85 51.85 50.90
$`./150601_0002.csv`
[1] 70.77 70.54 70.47 ...
...
[241] ... 51.00 51.17 51.43
$`./150601_0003.csv`
[1] 68.32 67.80 67.33 ...
...
[241] ... 50.58 50.68 50.77
How may I apply rbind() to all of these in one shot?
回答1:
Dont have reputation to add a comment so adding an answer
try this to rbind all data into one dataframe
Output<-do.call(rbind, list)
回答2:
How about
unlist(lapply(myfiles_data, `[[`, 2))
来源:https://stackoverflow.com/questions/31558630/rbind-all-given-columns-within-a-list