I am trying to plot graphs by loop.
Input data: Tables, which have the same ending *depth.txt, there are 2 tab delimited columns in the table:
Baba"\t"58.38
Tata"\t"68.38
Mama"\t"30.80
jaja"\t"88.65
OUTPUT: I would like to get a jpeg file with plot() for each *depth.txt (their names will be the same as the tables' names) for all files (axis x will be the first column from the table and axis y will be second column)
I created a part of the script, but it doesn't work:
files <- list.files(path="/home/fil/Desktop/", pattern="*depth.txt", full.names=T,recursive=FALSE)
for (i in 1:length(files))
plot(read.table(files[i],header=F,sep="\t")$V1,read.table(files[i],header=F,sep="\t")$V2)
dev.copy(jpeg,filename=files[i])
dev.off
It doesn't work, could you help me please? I am a beginner with R.
Will the following do what you want?
for (i in 1:length(files)) {
dat <- read.table(files[i], header = FALSE, sep = '\t')
jpeg(file = paste(files[i], '.jpeg', sep = ''))
plot(dat$V1, dat$V2)
dev.off()
}
Similar to the first two but changing the file name for the plots
files <- paste("fil",1:3,"depth.txt",sep="") # example file names
for( i in 1:length(files)) {
filename <- sub(".txt",".jpg",files[i])
jpeg(file=filename)
plot(1:(10*i)) # example plots
dev.off()
}
renameing the file?
for (i in 1:length(files)) {
file = files[i]
file = paste("jpg",file,sep="_")
jpeg(file)
plot(read.table(files[i],header=F,sep="\t")$V1,read.table(files[i],header=F,sep="\t")$V2)
dev.off()
}
Related
I'm new to R and very new to Stack Overflow.
I'm trying to read multiple PDF files into different text files. Because of the PDF, I have to convert them into PNG first. Then I want to extract the text from each PNG from the same PDF into a text file.
So the output would look like:
text_file_1: pdf1_png1, pdf1_png2, ...
text_file_2: pdf2_png1, pdf2_png2, ...
The code I have so far is:
files <- list.files(pattern = "pdf", full.names=TRUE)
for (i in files) {
for (j in i) {
pngfile_i <- pdftools::pdf_convert(i, dpi = 600)
text_i <- tesseract::ocr(pngfile_1)
filename <- paste(i,".txt",sep = "")
capture.output(text_i, filename, append = TRUE)
}
}
But honestly, I'm not sure if I need separate text files. If I can have an output of a table with the pdf title and then the text, that would solve the problem too.
Any help is appreciated! Thank you!
You can consider an approach like this :
files <- list.files(pattern = "pdf", full.names=TRUE)
nb_Files <- length(files)
list_Text <- list()
for(i in 1 : nb_Files)
{
list_Text[[i]] <- pdftools::pdf_text(files[i])
file_Name <- paste0("file", i, ".txt")
con <- file(file_Name)
writeLines(list_Text[[i]], con = con)
}
I am so close to getting my code to work, but cannot seem to figure out how to get a dynamic file name. Here is what Ivve got:
require(ncdf)
require(raster)
require(rgdal)
## For multiple files, use a for loop
## Input directory
dir.nc <- 'inputdirectoy'
files.nc <- list.files(dir.nc, full.names = T, recursive = T)
## Output directory
dir.output <- 'outputdirectory'
## For simplicity, I use "i" as the file name, but would like to have a dynamic one
for (i in 1:length(files.nc)) {
r.nc <- raster(files.nc[i], varname = "precipitation")
writeRaster(r.nc, paste(dir.output, i, '.tiff', sep = ''), format = 'GTiff', prj = T, overwrite = T)
}
## END
I appreciate any help. So close!!
You can do this in different ways, but I think it is generally easiest to first create all the output filenames (and check if they are correct) and then use these in the loop.
So something like this:
library(raster)
infiles <- list.files('inputpath', full.names=TRUE)
ff <- extension(basename(infiles), '.tif')
outpath <- 'outputpath'
outfiles <- file.path(outpath, ff)
To assure that you are writing to an existing folder, you can create it first.
dir.create(outpath, showWarnings=FALSE, recursive=TRUE)
And then loop over the files
for (i in 1:length(infiles)) {
r <- raster(infiles[i])
writeRaster(r, paste(outfiles[i], overwrite = TRUE)
}
You might also use something along these lines
outfiles <- gsub('in', 'out', infiles)
Here is the code that finally worked:
# Imports
library(raster)
#Set source file
infiles <- list.files('infilepath', full.names=TRUE)
#create dynamic file names and choose outfiles to view list
ff <- extension(basename(infiles), '.tif')
outpath <- 'outfilepath'
outfiles <- file.path(outpath, ff)
#run da loop
for (i in 1:length(infiles)) {
r <- raster(infiles[i])
writeRaster(r, paste(outfiles[i]), format ='GTiff', overwrite = T)
}
## END
I have several hundred data files and I need to add a header (start of the data in a file) and footer (end of the data in a file) to each file in r like following:
Header:
line1
line2
line3
likewise, I have few lines that I like to add the footer at the end of each data file
footer:
line1
line2
line3
while writing a table in r with write.table(). Can someone suggest a simple solution? Thanks
Perhaps something like this:
lapply( c('dobjt1', 'dobjct2', 'other3'),
function(x) {
name <- paste0( x, ".txt")
write(c(line1,line2,line3), file=name)
out <- get(x); Need to use `get` when working with character values
write.table(out, file=name, append=TRUE)
write(c(line1,line2,line3), file=name, append=TRUE)
})
Adding steps to #42- s solution to read a list of files from disk and assign their file names as the data frame names leads to a complete, working solution.
We'll use the Pokémon data from Alex Barradas Pokémon Stats data set from kaggle.com as our example.
download.file("https://github.com/lgreski/PokemonData/raw/master/pokemonData.zip",
"pokemonData.zip",mode="wb",method="wininet")
unzip("pokemonData.zip")
thePokemonFiles <- list.files("./pokemonData",
full.names=FALSE)[1:3] # subset to first 3 files
pokemonData <- lapply(thePokemonFiles,function(x) {
data <- read.csv(paste("./pokemonData/",x,sep=""))
# set input file name as object name so file list can be used in lapply() for write
assign(x,data,parent.env(environment()))
NULL # null return to avoid duplicating data frames in output list
})
header <- c("header 1","header 2","header 3")
footer <- c("footer 1","footer 2","footer 3")
lapply(thePokemonFiles, function(x) {
name <- paste0(x, ".txt")
write(header, file = name)
write.table(get(x), file = name, append = TRUE)
write(footer, file = name, append = TRUE)
})
...and the first few lines of the resulting text file for the first generation Pokémon is:
I am trying to get concatenate text files from url but i don't know how to do this with the html and the different folders?
This is the code i tried, but it only lists the text files and has a lot of html code like this How do I fix this so that I can combine the text files into one csv file?
library(RCurl)
url <- "http://weather.ggy.uga.edu/data/daily/"
dir <- getURL(url, dirlistonly = T)
filenames <- unlist(strsplit(dir,"\n")) #split into filenames
#append the files one after another
for (i in 1:length(filenames)) {
file <- past(url,filenames[i],delim='') #concatenate for urly
if (i==1){
cp <- read_delim(file, header=F, delim=',')
}
else{
temp <- read_delim(file,header=F,delim=',')
cp <- rbind(cp,temp) #append to existing file
rm(temp)# remove the temporary file
}
}
here is a code snippet that I got to work for me. I like to use rvest over RCurl, just because that's what I've learned. In this case, I was able to use the html_nodes function to isolate each file ending in .txt. The result table has the times saved as character strings, but you could fix that later. Let me know if you have any questions.
library(rvest)
library(readr)
url <- "http://weather.ggy.uga.edu/data/daily/"
doc <- xml2::read_html(url)
text <- rvest::html_text(rvest::html_nodes(doc, "tr td a:contains('.txt')"))
# define column types of fwf data ("c" = character, "n" = number)
ctypes <- paste0("c", paste0(rep("n",11), collapse = ""))
data <- data.frame()
for (i in 1:2){
file <- paste0(url, text[1])
date <- as.Date(read_lines(file, n_max = 1), "%m/%d/%y")
# Read file to determine widths
columns <- fwf_empty(file, skip = 3)
# Manually expand `solar` column to be 3 spaces wider
columns$begin[8] <- columns$begin[8] - 3
data <- rbind(data, cbind(date,read_fwf(file, columns,
skip = 3, col_types = ctypes)))
}
I have created multiple plots that are saved in a list.
Now I want to save them keeping the name they have on the list.
My code until now is as follows.
pdfplots <- function(PlotList){
L <- List()
for (i in 1:length(L)){
names(L[[i]]) <- paste0(names(PlotList), i)
pdfPath <- (file = "~/Documents/MyFile/MyPlots, names(L[[i]])")
myplot <- boxplot(PlotList[[i]])
}
dev.off()
}
As a result I want to get a pdf plot saved on a specific path.
Any help will be deeply apreciated
You should use pdf function. The chunk below should be doing the job:
pdfplots <- function(PlotList){
for (i in 1:length(PlotList)){
fullFileName = paste0("~/Documents/MyFile/MyPlots/", names(PlotList)[i],".pdf")
pdf(fullFileName)
boxplot(PlotList[[i]])
dev.off()
}
}