r - 为 ggplot2 组织物理实验数据

标签 r ggplot2 physics

我目前正在尝试使用 ggplot2 来可视化简单电流-电压实验的结果。当然,我在一组数据上取得了很好的结果。

但是,我有许多电流-电压数据集,我在 R 中递归输入这些数据集以获得以下组织(请参阅最少的代码):

data.frame(cbind(batch(string list), sample(string list), dataset(data.frame list)))

编辑:我的数据存储在名为batchname_samplenumber.txt的文本文件中,其中包含电压和电流列。我用来导入它们的代码是:

require(plyr)
require(ggplot2)

#VARIABLES
regex <- "([[:alnum:]_]+).([[:alpha:]]+)"
regex2 <- "G5_([[:alnum:]]+)_([[:alnum:]]+).([[:alpha:]]+)"

#FUNCTIONS
getJ <- function(list, k) llply(list, function(i) llply(i, function(i, indix) getElement(i,indix), indix = k))

#FILES
files <- list.files("Data/",full.names= T)

#NAMES FOR FILES
paths <- llply(llply(files, basename),function(i) regmatches(i,regexec(regex,i)))
paths2 <- llply(llply(files, basename),function(i) regmatches(i,regexec(regex2,i)))
names <- llply(llply(getJ(paths, 2)),unlist)
batches <- llply(llply(getJ(paths2, 2)),unlist)
samples <- llply(llply(getJ(paths2, 3)),unlist)

#SETS OF DATA, NAMED
sets <- llply(files,function(i) read.table(i,skip = 0, header = F))
names(sets) <- names
for (i in as.list(names)) names(sets[[i]]) <- c("voltage","current")

df<-data.frame(cbind(batches,samples,sets))    

并且可以通过以下方式生成最少的数据:

require(plyr)

batch <- list("A","A","B","B")
sample <- list(1,2,1,2)
set <- list(data.frame(voltage = runif(10), current = runif(10)),data.frame(voltage = runif(10), current = runif(10)),data.frame(voltage = runif(10), current = runif(10)),data.frame(voltage = runif(10), current = runif(10)))

df<-data.frame(cbind(batch,sample,set))

我的问题是:是否可以使用数据按原样使用类似于以下代码(不起作用)进行绘图?

ggplot(data, aes(x = dataset$current, y = dataset$voltage, colour = sample)) + facet_wrap(~batch)

更通用的版本是:ggplot2 是否能够处理原始物理数据,而不是离散统计数据(如钻石、汽车)?

最佳答案

对于新定义的问题(名为“batchname_samplenumber.txt”的两列文件),我建议采用以下策略:

read_custom <- function(f, ...) {
 d <- read.table(f, ...)
 names(d) <- c("V", "I")
 ## extract sample and batch from the base filename
 ids <- strsplit(gsub(".txt", "", f), "_")
 d$batch <- ids[[1]][1]
 d$sample <- ids[[1]][2]
 d
}

## list files to read
files <- list.files(pattern=".txt")
## read them all in a single data.frame
m <- ldply(files, read_custom)

关于r - 为 ggplot2 组织物理实验数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9864096/

相关文章:

r - 通过引用传递给函数时处理 R data.table 中的无效 selfref

R data.table 在使用.I 获取行号时返回 NA

r - 使用 R 中的 for 循环为每个因素打印多个 ggplots

iphone - 月球着陆器游戏需要哪些数学知识?

r - 使用 R 以最少的磁盘使用量存储单个长字符串

r - 将汇总表矩阵划分为R中的几个表矩阵

R - 添加质心到散点图

r - ggplot2中的中值回归线

c# - 转换为 3D 后速度反射不再起作用

c++ - 乒乓物理题