Pardons if this has already been answered, I didn't see anything quite like this. I want to create a running log but I can't get the write function to append. Here is a sample:
fName <- "D:/Temp/foo.txt"
fCn <- file(fName)
write('test1', fCn, append = TRUE)
write('test2', fCn, append = TRUE)
close(fCn)
When I open the resulting file I only see the last line. I have also tried opening and closing the file like so:
fCn <- file(fName)
write('test1', fCn, append = TRUE)
close(fCn)
fCn <- file(fName)
write('test2', fCn, append = TRUE)
close(fCn)
Seems like it should be easy. Where am I going wrong? TIA
Open the connection in append mode:
> fCn <- file(fName,open="a")
Full example:
> fName="out1.txt"
> fCn <- file(fName,open="a")
> write('test1', fCn, append = TRUE)
> write('test2', fCn, append = TRUE)
> close(fCn)
Results in both strings written to the file.
Alternatively you can just write to the file name (not a connection object) with append=TRUE:
> write('test1', "out2.txt", append = TRUE)
> write('test2', "out2.txt", append = TRUE)
also results in a two-line output file, created from scratch.
You can use sink for this purpose. It is always easier to write what you can actually see in R console to a text file so you are sure about the output.
sink("C:/Users/mahdisoltanim/Desktop/a.txt", append= TRUE)
cat("\n")
cat("test1")
cat("\n")
cat("test2")
sink()
Related
I am trying to store the results of the function below,
I could only print the results but cannot save it as csv format. how can i save these results into a csv file?
Thanks in advance!!!
calEAD=function(loan, R, final, startdate, first_enddate,enddate){
I=loan*R
start=as.Date(startdate)
firstend=as.Date(first_enddate)
p=firstend-start
period=as.numeric(p)/365
EADabc=0
b=enddate-2017
for(i in (0:b)){
EADabc=I/((1+R)**(i+period))+EADabc
print(EADabc)}
}
calEAD1=calEAD(6690012.88,0.0588,6690012.88, '2016-12-31','2017-08-29',2022)
calEAD2=calEAD(385000.12,0.0588,385000.12, '2016-12-31','2017-09-11',2023)
It seems that you want to keep every intermediate result of EADabc inside the for loop. In that case you could concatenate them to a vector like this:
calEAD=function(loan, R, final, startdate, first_enddate,enddate){
I=loan*R
start=as.Date(startdate)
firstend=as.Date(first_enddate)
p=firstend-start
period=as.numeric(p)/365
EADabc=0
b=enddate-2017
# Define an empty vector
result = c()
for(i in (0:b)){
EADabc=I/((1+R)**(i+period))+EADabc
# Append the current result to the vector
result = c(result,EADabc)
}
# Make the function return this vector
result
}
Result:
calEAD1=calEAD(6690012.88,0.0588,6690012.88, '2016-12-31','2017-08-29',2022)
calEAD2=calEAD(385000.12,0.0588,385000.12, '2016-12-31','2017-09-11',2023)
> calEAD1
[1] 378809 736581 1074484 1393622 1695037 1979713
> calEAD2
[1] 21755.57 42302.95 61709.24 80037.81 97348.51 113697.87 129139.28
If you want to save them to a csv file, do:
write.csv(x = calEAD1, file = "test.csv")
You can use write.csv or the write.table functions.
for(i in (0:b))
{
EADabc=I/((1+R)**(i+period))+EADabc
write.table(EADabc, file = "file_name.csv",sep = ",", col.names = T, append =T)
}
Or
write.csv(EADabc, file = "file_name.csv", row.names = FALSE)
the following code in R for all the files. actually I made a for loop for that but when I run it it will be applied only on one file not all of them. BTW, my files do not have header.
You use [[ to subset something from peaks. However, after reading it using the file name, it is a data frame with then no more reference to the file name. Thus, you just have to get rid of the [[i]].
for (i in filelist.coverages) {
peaks <- read.delim(i, sep='', header=F)
PeakSizes <- c(PeakSizes, peaks$V3 - peaks$V2)
}
By using the iterator i within read.delim() which holds a new file name each time, every time R goes through the loop, peaks will have the content of a new file.
In your code, i is referencing to a name file. Use indices instead.
And, by the way, don't use setwd, use full.names = TRUE option in list.files. And preallocate PeakSizes like this: PeakSizes <- numeric(length(filelist.coverages)).
So do:
filelist.coverages <- list.files('K:/prostate_cancer_porto/H3K27me3_ChIPseq/',
pattern = 'island.bed', full.names = TRUE)
##all 97 bed files
PeakSizes <- numeric(length(filelist.coverages))
for (i in seq_along(filelist.coverages)) {
peaks <- read.delim(filelist.coverages[i], sep = '', header = FALSE)
PeakSizes[i] <- peaks$V3 - peaks$V2
}
Or you could simply use sapply or purrr::map_dbl:
sapply(filelist.coverages, function(file) {
peaks <- read.delim(file, sep = '', header = FALSE)
peaks$V3 - peaks$V2
})
I am trying to perform the following:
Analyse_Store <- function("x"){
datapaste"x" <- read.table(file = "x".txt, sep=";", header = TRUE)
}
So basically I am trying to read a table named "x" and assign it to the name datapaste"x" unfortunately this does not work as expected and I cannot find any help online.
Thanks in advance
Use assign to read table into the variable named x.
The following function will take argument x and assign x.txt from working directory to a variable x inside the function.
Analyse_Store <- function(x){
assign(paste("datapaste",x,sep=""), read.table(file = paste(x,".txt",sep=""), sep=";", header = TRUE))
}
Usage would be
datapastex = Analyse_Store("x")
Unless you are further processing the table inside the function, I don't see much use for a function in this case. You could just do
datapastex = read.table(file = "x.txt", sep=";", header = TRUE)
My script reads in a list of text files from a folder. A calculation for all values in a few columns in each text file is made.
At the end I want to write the resulting data.frame into a new text file in a different location.
The problem is, that the script keeps overwriting the file it created before. So I end up with only one file (the last one that was read in).
But I don't get what I am doing wrong here. The output file name is different each time, so in my head it should produce separate files.
The script looks as follows:
RAW <- "C:/path/tofiles"
files <- list.files(RAW, full.names = TRUE)
for(j in length(files)) {
if(file.exists(files[[j]])){
data <- read.csv(files[[j]], skip = 0, header=FALSE)
data[9] <- do.call(cbind,lapply(data[9], function(x){(data[9]*0.01701)/0.00848}))
data[11] <- do.call(cbind,lapply(data[11], function(x){(data[11]*0.01834)/0.00848}))
data[13] <- do.call(cbind,lapply(data[13], function(x){(data[13]*0.00982)/0.00848}))
data[15] <- do.call(cbind,lapply(data[15], function(x){(data[15]*0.01011)/0.00848}))
OUT <- paste("C:/path/to/destination_folder",basename(files[[j]]),sep="")
write.table(data, OUT, sep=",", row.names = FALSE, col.names = FALSE, append = FALSE)
}
}
The problem is in your for loop. length(files) just provides 1 value, namely the length of your files-vector, while I think you want to have a sequence with that length.
Try seq_along or just for(j in files).
I built the following R script to take a .csv generated by an automated report and split it into several .csv files.
This code works perfectly, and outputs a .csv file for each unique value of "facility" in "todays_data.csv":
disps <- read.csv("/Users/me/Downloads/todays_data.csv", header = TRUE, sep=",")
for (facility in levels(disps$Facility)) {
temp <- subset(disps, disps$Facility == facility & disps$Alert.End == "")
temp <- temp[order(temp$Unit, temp$Area),]
fn <- paste("/Users/me/Documents/information/", facility, "_todays_data.csv", sep = "")
write.csv(temp, fn, row.names=FALSE)
}
But this does not output anything:
args <- commandArgs(trailingOnly = TRUE)
file <- args[1]
disps <- read.csv(file, header = TRUE, sep=",")
for (facility in levels(disps$Facility)) {
temp <- subset(disps, disps$Facility == facility & disps$Alert.End == "")
temp <- temp[order(temp$Unit, temp$Area),]
fn <- paste("/Users/me/Documents/information/", facility, "_todays_data.csv", sep = "")
write.csv(temp, fn, row.names=FALSE)
}
The only difference between the two files is that the first hardcodes the path to the .csv file to be split, while the second one has it passed as an argument in the command line using Rscript.
The read.csv() command works with the passed file path, because I can successfully run commands like head(disps) while running the script via Rscript.
Nothing within the for-loop will execute when run via Rscript, but things before and after it will.
Does anyone have any clues as to what I've missed? Thank you.