Reputation: 337
I'm working in RStudio, trying to produce some simple graphs and correlations. This is probably a super simple fix but I can't seem to loop through my files and produce plots. See below for files, loop, and sample data frame
> 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
I understand that it's seeing "files" as a character vector, but I'm not sure why that's a problem when passed to the loop.
Upvotes: 0
Views: 478
Reputation: 5405
Passing a string as a character vector when a function (ggplot
here) wants a data.frame
won't work in the loop for the same reason it won't work out of the loop...R doesn't know to retrieve the object given the name from the global environment.
I would suggest (similar to @patL's comment) retrieving the object and then running the loop:
for(i in files){
dat <- get(i) # new line
plt <- ggplot(dat, aes_string(x="Five", y = "Three")) +
...
}
It should be noted that ls()
will return a character vector of all objects in the environment, regardless of their class, so if you have anything else defined, you may run into issues there. From the looks of it you may be able to use the pattern
argument to ls()
to ensure you at least return a vector of object names matching specific patterns.
Upvotes: 1