R – 过滤不需要的数据后,自动从一些csv文件中创build散点图

我附上一个样本CSV文件,我有100个,

它的许多列及其19行应该被过滤,其余的数据应该被用来绘制图表并以更有用的格式导出图表。

这些数据是由Netlogo行为空间生成的,我找不到直接显示输出的好方法,所以每次实验后我都有很多csv文件。

数据文件: https : //www.dropbox.com/s/nj243qcs6sx6fu8/Rates.csv示例输出: https : //www.dropbox.com/s/suomh0vwsfzisj4/SampleGraph.jpg

例如大胆的列是我需要绘制的那些:

x,y ,颜色,下笔,x, y ,颜色,下笔,x, y ,颜色,下笔,x, y ,颜色,下笔?

谢谢 ;)

这是这个情节的答案:

dat <- read.csv('Rates.csv', stringsAsFactors = FALSE, skip = 19) colnames(dat)[which(names(dat) %in% c("y", "y.1", "y.2", "y.3"))] <- c("Age", "Revenge", "Homicide", "Hunger") require(reshape2) tmp <- melt(dat, id.vars = "x", measure.vars = c("Age", "Revenge", "Homicide", "Hunger")) require(ggplot2) ggplot(tmp,aes(x, value)) + geom_point(aes(colour = factor(variable))) + xlab("time") + ylab("units") + ggtitle("My CSV file") + labs(colour = "my variables") 

在这里输入图像描述

这里是你如何使用你的数百个CSV文件…

 files <- (dir("C:/my-csv-files", recursive=TRUE, full.names=TRUE, pattern="\\.(csv|CSV)$")) listcsvs <- lapply(files, function(i) read.csv(i, stringsAsFactors = FALSE, skip = 19)) names(listcsvs) <- files require(reshape2) require(ggplot2) for (i in 1:length(files)) { tmp <- melt(dat, id.vars = "x", measure.vars = c("y", "y.1", "y.2", "y.3")) print( ggplot(tmp,aes(x, value)) + geom_point(aes(colour = factor(variable))) + xlab("time") + ylab("units") + ggtitle(names(listcsvs[i])) ) ) } 

在不知道文件的命名结构的情况下,我无法确定这将如何捕获它们。 下面的代码会将当前目录中的所有.csv文件绘制出来,并在同一个目录中创build一个.png文件,其文件名与.csv相同(除了后缀)。

 # get list of .csv files files <- dir(".", pattern = "\\.csv", full.names = TRUE, ignore.case = TRUE) # we'll use ggplot2 for plotting and reshape2 to get the data in shape library(ggplot2) library(reshape2) # loop through the files for (file in files) { # load the data, skipping the first 19 lines df <- read.csv(file, as.is=T, skip=19) # keep only the columns we want df <- df[,c(1,2,6,10,14)] # put the names back in names(df) <- c('x','Age','Revenge','Homicide','Hunger') # convert to long format df <- melt(df, id=c('x')) # create the png nam name <- gsub(file, pattern='csv', replacement='png') # begin png output png(name, width=400, height=300) # plot p <- ggplot(df, aes(x=x, y=value, colour=variable)) + # line plot geom_line() + # use the black and white theme theme_bw() + xlab('x label') + ylab('y label') # we have to explicitly print to png print(p) # finish output to png dev.off() } 

来自Rates.csv的示例输出图

这应该让你开始:

 Df <- read.csv('https://dl.dropboxusercontent.com/s/nj243qcs6sx6fu8/Rates.csv?dl=1&token_hash=AAEvqZvmuesLhKJSrYHiasj-h0ULrABzbU0Q39bU6FJSCQ', skip=19) X <- as.matrix(Df[,grep("x",names(Df))]) Y <- as.matrix(Df[,grep("y",names(Df))]) matplot(X, Y, type="l", lty=1) 

在这里输入图像说明

如果你把它放到一个循环中,你可以为你的所有文件生成图表。