【问题标题】:looping a data frame to create a boxplot循环数据框以创建箱线图
【发布时间】:2015-08-12 07:57:01
【问题描述】:

我正在尝试在数据框中使用 R 软件获取箱线图,但有很多列附加到数据框中。 这是代码

path = "E:/plot/2"
fileList = list.files(path=path,pattern="\\.teTestResult",full.names=T)
myfiles = lapply(fileList, read.csv,header=TRUE,sep=";" )

a <- data.frame(myfiles)
attach(a)
boxplot(Return~gama)
boxplot(Return~theta)
boxplot(Return~detectionsLimit)
boxplot(Return~NSMOOTH)
boxplot(Return~NREF)
boxplot(Return~NOBS)
boxplot(Return.1~gama.1)
boxplot(Return.1~theta.1)
boxplot(Return.1~detectionsLimit.1)
boxplot(Return.1~NSMOOTH.1)
boxplot(Return.1~NREF.1)
boxplot(Return.1~NOBS.1)
...
boxplot(Return.9~NOBS.9)

这段代码有效,但它没有提供一个好的代码,因为它很长。我如何使用 R 来简化它? 非常感谢您的帮助

~更新~

我正在尝试使用 for 循环,因为我尝试进行箱线图的变量名称仅在数字上有所不同,所以在这里

for (i in 1:9){
boxplot(Return.[i]~gama.[i])
    }

但是,这样说发生了错误

Error in eval(expr, envir, enclos) : object 'Return.' not found 

我仍然看到 R 编程存在很多问题 非常感谢您的回复。

【问题讨论】:

  • 请提供你的data.frame的变量名;我猜你访问变量的方式是错误的,你错过了 a$ 并且应该输入boxplot(with(a, get(paste0("Return.", [i]))) ~ with(a, get(paste0("gama.", [i])))
  • @grrgrrbla 感谢您的回复,我已尝试使用 attach(a) 函数替换 a$。我已经尝试过你的代码for(i in 1:9){ boxplot(with(a, get(paste0("Return.", [i]))) ~ with(a, get(paste0("gama.", [i]))) },但我遇到了来自[] 的错误,它是这样说的,Error: unexpected '[' in: "for(i in 1:9){ boxplot(with(a, get(paste0("Return.", [
  • 你(也包括我)忘记了) 检查所有这些,请自己考虑一下

标签: r data-visualization boxplot


【解决方案1】:

如果您将数据框列表与 data.frame() 函数结合使用,您将绑定数据框。如果所有文件都具有相同的结构,我建议您使用 rbind 将它们组合起来:

library(dplyr)
for(i in 1:length(myfiles)) myfiles[[i]]$nr = i   # if you need to know the origin of the data
df = bind_rows(myfiles)

不同文件之间的区别可以通过分面来完成,但由于您需要不同变量的绘图,因此您可能无法进一步缩短代码:

library(ggplot2)
ggplot(df, aes(factor(gama), Return)) + geom_boxplot() + facet_wrap(~ nr)
ggplot(df, aes(factor(theta), Return)) + geom_boxplot() + facet_wrap(~ nr)
ggplot(df, aes(factor(detectionsLimit), Return)) + geom_boxplot() + facet_wrap(~ nr)
ggplot(df, aes(factor(NSMOOTH), Return)) + geom_boxplot() + facet_wrap(~ nr)
ggplot(df, aes(factor(NREF), Return)) + geom_boxplot() + facet_wrap(~ nr)
ggplot(df, aes(factor(NOBS), Return)) + geom_boxplot() + facet_wrap(~ nr)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-28
    • 2021-12-27
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2021-12-07
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多