I am new to the programming world and need help with loading a file to R and creating a matrix with it. I can import individual files and create and individual matrix out of it. How do I do this for multiple files? I have 21 files that each contain 100 rows and 100 columns and I need to import each file and put everything in a single array.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
- I would use
list.files
to list my files by pattern. lapply
to loop through the list of files and create a list data.frame withread.csv
rbindlist
to bind all in a big matrix.temp = list.files(pattern="*.csv") named.list <- lapply(temp, read.csv) library(data.table) files.matrix <-rbindlist(named.list)
回答2:
It's not exactly clear what structure you want. You can choose between a 2100x100 matrix or a 2100x100 dataframe or a 100x 100x 21 array or a list with 21 entries each of which was 100 x 100. (In R an array is the term one would use for a regular 3 dimensional structure with columns all of that same type. (and then of course there is agstudy's suggestion that you use a data.table.)
In a sense agstudy's code already gives you the 21 item list of dataframes each of dimension: 100x100:
temp = list.files(pattern="*.csv")
named.list <- lapply(temp, read.csv)
To get 100 x 100 x 21 array continue with this:
require(abind)
arr <- abind(named.list)
To get the 2100 x 100 dataframe, continue instead with:
longdf <- do.call(rbind, named.list)
To get the 2100 x 100 matrix continue from the last line with:
longmtx <- data.matrix(longdf)