![](/img/trans.png)
[英]Reading multiple csv files and getting the filename of each csv file in R
[英]Import multiple csv files into R and plot pairs of data from each csv file on the same graph
我想導入多個 csv 文件 (12),其中包含時間 t 和壓力 P 的數據。每個文件的標題相同 (t,P) 但時間值不常見,因此每個 csv 中的每個 t,P 對文件是唯一的。
我可以毫無問題地導入文件:
filenames <- list.files(path = ("C:/Users/K125763/Documents/Mars"),
# Follows a regular expression that matches:
pattern = "mars-[0-12]{2}.csv",
full.names = TRUE)
filenames <- filenames[1:12]
但是下面的循環將每個數據對繪制在單獨的圖表上:
analyze.p <- function(filename) {
dat <- read.csv(file = filename, header = TRUE)
plot(dat$P~dat$t)
}
for (f in filenames) {
print(f)
analyze.p(f)
}
如何在同一個圖表上獲取所有數據對?
我會建議一種函數式編程方法 + ggplot2
:
library(purrr) # functional programming tools
library(dplyr) # data wrangling
library(ggplot2) # plotting
filenames <- list.files(path = ("C:/Users/K125763/Documents/Mars"),
# Follows a regular expression that matches:
pattern = "mars-[0-12]{2}.csv",
full.names = TRUE)
filenames <- filenames[1:12]
## Read and concatenate CSV files
data <- filenames %>%
map_df(~mutate(read.csv(file = .x, header = TRUE), source_file = .x))
## Plot in a single chart
ggplot(data, aes(t, P)) +
geom_point() +
facet_wrap('source_file')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.