how to save RDS file with different title in r? - r

I have want to save the cars data in a loop with different title name.
for (i in 1:10)
{ outfilename=paste0(i ,".RDS")
saveRDS(cars, file = "/home/outfilename.RDS")}
however, it looks like the out filename still did not work

You probably meant something like this:
for (i in 1:10){
outfilename <- paste0("/home/", i ,".RDS")
saveRDS(cars, file = outfilename)
}

Using lapply
lapply(1:10, function(i)
saveRDS(cars, file = file.path('/home', paste0(i, ".RDS"))))

Related

Dynamic files name load and processing with for loop

I'm processing some .xlsx, there are named like time1_drug1,time1_drug2,until tiume6_drug5 (30 files in total). I want to load these xlsx to R and name them to dataset such as t1d1, t2d2.
I tried to use sprintf, but I cannot figure out how to make valid.
for(i in 1:6) {
for(j in 1:5) {
sprintf("time%i","drug%j,i,j)=read.xlsx("/Users/pathway/dataset/time_sprintf(%i,i)_drug(%j,j).xlsx", 1)}
names(sprintf("t%i","d%j,i,j))=c("result", "testF","TestN")
sprintf("t%i","d%j,i,j)$Discription[which(sprintf("t%i","d%j,i,j)$testF>=1&sprintf("t%i","d%j,i,j)$TestN>=2)]="High+High"
}
}
I expect to get 30 data like t1d1 till t6d5.
You should (almost) never use assign. When reading multiple files into R you should (almost) always put them in a named list.
A rough outline of a much better approach is this:
# Put all the excel files in a directory and this retrieves all their paths
f <- dir("/Users/pathway/dataset/",full.names = TRUE)
# Read all files into a list
drug_time <- lapply(X = f,FUN = read.xlsx)
# Name each list element based on the file name
names(drug_time) <- gsub(pattern = ".xlsx",replacement = "",x = basename(f),fixed = TRUE)
You can use the for loop as you are, but you should also use the assign function:
for(i in 1:6){
for(j in 1:5){
assign(paste0('t', i, '_', 'd', j), read.xlsx(paste0("/Users/pathway/dataset/time_",i,"_drug",j,".xlsx"), 1))
}
}

Extract the line with the same content from two files in R

I would like to use readLines function to read the text file line by line
69C_t.txt
Also, I would like to write a simple for loop with condition to extract the identical lines in two files.
69C_t <- "69C_t.txt"
conn <- file(69C_t,open="r")
t <-readLines(conn)
69C_b <- "69C_b.txt"
conn <- file(69C_b,open="r")
b <-readLines(conn)
for (i in 1:length(t)){
for (j in 1:length(b)){
if (i==j)
write(t[i], file = "overlap.txt")
}
}
close(tumor)
However, it seems only print out the first line.
Can someone please have a check ?
A faster approach would be, instead of the loop
writeLines(t[t %in% b],"overlap.txt")
How about adding append in the write function:
write(t[i], file = "overlap.txt", append = TRUE)

saving pdf plots in a specific file in r

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()
}
}

Looping through files in R and applying a function

I'm not a very experienced R user. I need to loop through a folder of csv files and apply a function to each one. Then I would like to take the value I get for each one and have R dump them into a new column called "stratindex", which will be in one new csv file.
Here's the function applied to a single file
ctd=read.csv(file.choose(), header=T)
stratindex=function(x){
x=ctd$Density..sigma.t..kg.m.3..
(x[30]-x[1])/29
}
Then I can spit out one value with
stratindex(Density..sigma.t..kg.m.3..)
I tried formatting another file loop someone made on this board. That link is here:
Looping through files in R
Here's my go at putting it together
out.file <- 'strat.csv'
for (i in list.files()) {
tmp.file <- read.table(i, header=TRUE)
tmp.strat <- function(x)
x=tmp.file(Density..sigma.t..kg.m.3..)
(x[30]-x[1])/29
write(paste0(i, "," tmp.strat), out.file, append=TRUE)
}
What have I done wrong/what is a better approach?
It's easier if you read the file in the function
stratindex <- function(file){
ctd <- read.csv(file)
x <- ctd$Density..sigma.t..kg.m.3..
(x[30] - x[1]) / 29
}
Then apply the function to a vector of filenames
the.files <- list.files()
index <- sapply(the.files, stratindex)
output <- data.frame(File = the.files, StratIndex = index)
write.csv(output)

Plot graphs in R by loop and save it like jpeg

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()
}

Resources