通过数据帧和绘制图表循环

问题描述 投票:0回答:1

我在RStudio工作,试图制造一些简单的图表和相关性。这可能是一个超级简单的修复,但我似乎无法遍历我的文件并生成图表。参阅下面的文件,循环,和样本数据帧

> ls()
 [1] "let-7b-5p"     "let_7a_5p"     "miR_125b_5p"   "miR_16_5p"    "miR_182_5p"    "miR_21_5p"    "miR_30e_5p"    "miR_320c_2_3p" "miR_92a_1_3p"  "miR_92b_3p"
[10]  "rRNA-45S"      "tRNA_3p_1"    "tRNA_5p_2"    
> files <- ls()
> for(i in files){
+   plt <- ggplot(`i`, aes_string(x="Five", y = "Three")) +
+       geom_point(shape=16) +
+       geom_smooth(method=lm) 
+   print(plt)
+   pearson <- cor.test(`i`$Five, `i`[, "Three"], method = "pearson", conf.level = 0.95)
+   print(pearson)
+ }
Error: `data` must be a data frame, or other object coercible by `fortify()`, not a character vector
> print(`let-7b-5p`)
       Five        Three       One
A      14.06       13.14       13.62
B      14.45       14.64       14.21
C       7.84       10.23        8.05
D      12.84       13.13       13.07
E      16.55       15.97       16.01
F      12.92       12.02       12.37

据我所知,它看到“文件”作为一个特征向量,但我不知道为什么传给循环时,这是一个问题。

r loops ggplot2
1个回答
1
投票

传递一个字符串时,函数(ggplot这里)想要一个data.frame不会在环路它不会工作圈外同样的原因工作特征向量... R不知道可检索给定对象从全球环境的名称。

我建议(类似@ patL的评论)检索对象,然后运行该循环:

for(i in files){
  dat <- get(i) # new line
  plt <- ggplot(dat, aes_string(x="Five", y = "Three")) + 
  ...
}

应当指出的是,ls()将返回环境中的所有对象的特征向量,不论其阶级的,所以如果你有别的定义,你可能会遇到的问题在那里。从外观上来看,你可能能够使用pattern参数ls(),以确保你至少返回匹配特定的模式对象名称的向量。

© www.soinside.com 2019 - 2024. All rights reserved.