我正在尝试绘制一张带有多个试验的图形(来自单独的文本文件)。在以下情况下,我将“位置”变量与“点火速率”变量一起绘制,当我单独使用ggplot时,它可以工作:
a <- read.table("trial1.txt", header = T)
library(ggplot2)
ggplot(a, aes(x = place, y = firing_rate)) + geom_point() + geom_path()
但是当我尝试创建一个for循环来遍历文件夹中的每个试用文件并将其绘制在同一张图上时,我遇到了问题。这是我到目前为止的内容:
files <- list.files(pattern=".txt")
for (i in files){
p <- lapply(i, read.table)
print(ggplot(p, aes(x = place, y = firing_rate)) + geom_point() + geom_path())
}
它给我一个“错误:data
必须是数据帧或fortify()
可强制执行的其他对象,而不是列表”消息。我是R的新手,所以我不确定该怎么做。
预先感谢您的帮助!
答案 0 :(得分:0)
通常,避免循环是R中最好的选择。由于您正在使用ggplot
,因此您可能会对使用tidyverse的map_df
函数感兴趣:
首先创建一个读取函数,并将文件名包含为试用标签:
readDataFile = function(x){
a <- read.table(x, header = T)
a$trial = x
return(a)
}
下一步map_df
:
dataComplete = map_df(files, readDataFile)
这会在每个文件上运行我们的小功能,并将它们全部组合到一个数据帧中(当然,假设它们在格式上兼容)。
最后,您可以像以前一样绘制,但可以根据试验变量进行区分:
ggplot(dataComplete, aes(x = place, y = firing_rate, color=trial, group=trial)) + geom_point() + geom_path()