I have a folder, which contains 70 files (in .xls
format). I would like to write a script in R, which makes plot from every .xls
file and saves it to separate .jpg
(or .png
) files. Is it possible? Give me a hint?
Asked
Active
Viewed 73 times
1 Answers
2
Something like this should work:
library(readxl)
fn <- list.files("yourfolder", pattern = "xlsx?$", full.names = T)
dfs <- lapply(fn, read_excel)
for (x in 1:length(dfs)) {
png(paste0(fn[x], ".png"))
with(dfs[[x]], {
plot(...)
})
dev.off()
}

lukeA
- 53,097
- 5
- 97
- 100
-
Can the `for` loop be replaced with `lapply`? – Brian P Apr 02 '15 at 12:45
-
I guess it can be replaced, but why should it? – lukeA Apr 02 '15 at 12:49
-
I have a problem with: " dfs <- lapply(fn, read_excel) " because object "fn" I have from the previous line, but what is it "read_excel" ? And I don't have library "readxl" ( I cant find this library in Rstudio to install it), so library "xlsx" will be ok? :) – monika_w091 Apr 02 '15 at 13:03
-
Have a look at [readxl](https://github.com/hadley/readxl): you prly need `install.packages("devtools"); devtools::install_github("hadley/readxl")`. – lukeA Apr 02 '15 at 13:07
-
@lukeA Still learning R, and regularly hear that `for` loops should generally be avoided. – Brian P Apr 02 '15 at 13:40
-
I have already installed package :) and I have question. When I write ggplot function I must point out data source ( ggplot(data ......... ) ) . I dont have idea what I should write in this place. And another question. :) Before I make plots I have to prepare my data and for this purpose I use function "melt" (from reshape package). How Can I put this in code? – monika_w091 Apr 02 '15 at 14:21
-
For ggplot, use `dfs[[x]]` as data argument. The rest: I dunno, because I don't know your data. Feel free to edit your original question and add it. Make sure to read http://adv-r.had.co.nz/Reproducibility.html and http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example before you post/edit. – lukeA Apr 02 '15 at 14:32