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)
Related
I am trying to add the name of each file in a list of .csv as the last column with all values also equal to the name. I am getting it, but the result show the files like transposed or something. I donĀ“t know how to fix it, I have tried data.frame, unlist, but nothing.
This is the code:
workbooks <- list.files(pattern="*.csv", full.names= T)
read_workbooks <- lapply(workbooks, read.csv)
for (i in 1:length(workbooks)){
name_of_file[i] <- str_replace_all(str_sub(workbooks[i], 3,
end = unlist(gregexpr("-current",workbooks[i]))-1),"_"," ")
temp_workbook <- cbind(read_workbooks[i],"Filer Name" = name_of_file[i])
write.csv(temp_workbook, file = paste(name_of_file[i],".csv",sep = ""),
row.names = F)
}
You can do this in the same lapply call with the help of an anonymous function.
workbooks <- list.files(pattern="*.csv", full.names= TRUE)
lapply(workbooks, function(x) {
write.csv(transform(read.csv(x), file_name = basename(x)),sprintf('new_%s.csv',
tools::file_path_sans_ext(basename(x))), row.names = FALSE)
})
Read each csv in workbooks, add a new column name in each file which is the name of the file and write the new csv.
I have managed to combined the data from several files and currently trying to extract a file number from my files and insert these into a column.
fnames = dir("../data/temperature_trials", full.names=TRUE)
print(fnames)
for (i in 1: length(fnames) ) {
#open each file in turn
temp = read.csv(fnames[i])
if (i == 1) {
res = temp
} else {
res = rbind(res, temp)
}
}
```
Imported 12 .csv files and used rbind to combine all data.Files named:
Trial1.csv
Trial2.csv
.
.
.
Trial12.csv
```
for (i in 1: length(fnames)) {
loc = regexpr(pattern = "Trial[0-9]*", text = fnames[i])
trialNumber = as.numeric(substr(fnames[i], start = loc[[1]][1]+5,
stop = loc[[1]][1] + attr(loc, 'match.length')-1))
print(trialNumber)
res1 = cbind(trialNumber, res)
```
I am trying to extract the trial numbers from each .csv file name and place them into a column named TrialNumber. When I do so it will only place a 12 into this column for every data point. Since it is using a loop I am assuming this is why, but can not figure out how to fix this or another way to do so. I need to assign the trial number to each data point corresponding with each .csv file.
Maybe you can simply add Trial number during each iteration of the loop-
for (i in 1: length(fnames) ) {
#open each file in turn
temp = read.csv(fnames[i])
if (i == 1) {
res = temp
} else {
res = rbind(res, temp)
}
res$trial_number=i
}
This way you will have a trial number column which will correspond to the file which had been imported.
You can also try extracting the numeric part of the file name as pointed out in this answer-
Extract numeric part of strings of mixed numbers and characters in R
I'd create a list of data frames from the CSV files, using the file name as the basis for each list element name:
fnames <- list.files("full/path/to/data/temperature_trials",
pattern = "*.csv", full.names = TRUE)
temp <- lapply(fnames, read.csv)
names(temp) <- tools::file_path_sans_ext(basename(fnames))
Then dplyr::bind_rows() will create a dataframe from the list with the treatment label in the .id column:
library(dplyr)
temp_df <- bind_rows(temp, .id = "TrialNumber")
I have a list of files like:
nE_pT_sbj01_e2_2.csv,
nE_pT_sbj02_e2_2.csv,
nE_pT_sbj04_e2_2.csv,
nE_pT_sbj05_e2_2.csv,
nE_pT_sbj09_e2_2.csv,
nE_pT_sbj10_e2_2.csv
As you can see, the name of the files is the same with the exception of 'sbj' (the number of the subject) which is not consecutive.
I need to run a for loop, but I would like to retain the original number of the subject. How to do this?
I assume I need to replace length(file) with something that keeps the original number of the subject, but not sure how to do it.
setwd("/path")
file = list.files(pattern="\\.csv$")
for(i in 1:length(file)){
data=read.table(file[i],header=TRUE,sep=",",row.names=NULL)
source("functionE.R")
Output = paste("e_sbj", i, "_e2.Rdata")
save.image(Output)
}
The code above gives me as output:
e_sbj1_e2.Rdata,e_sbj2_e2.Rdata,e_sbj3_e2.Rdata,
e_sbj4_e2.Rdata,e_sbj5_e2.Rdata,e_sbj6_e2.Rdata.
Instead, I would like to obtain:
e_sbj01_e2.Rdata,e_sbj02_e2.Rdata,e_sbj04_e2.Rdata,
e_sbj05_e2.Rdata,e_sbj09_e2.Rdata,e_sbj10_e2.Rdata.
Drop the extension "csv", then add "Rdata", and use filenames in the loop, for example:
myFiles <- list.files(pattern = "\\.csv$")
for(i in myFiles){
myDf <- read.csv(i)
outputFile <- paste0(tools::file_path_sans_ext(i), ".Rdata")
outputFile <- gsub("nE_pT_", "e_", outputFile, fixed = TRUE)
save(myDf, file = outputFile)
}
Note: I changed your variable names, try to avoid using function names as a variable name.
If you use regular expressions and sprintf (or paste0), you can do it easily without a loop:
fls <- c('nE_pT_sbj01_e2_2.csv', 'nE_pT_sbj02_e2_2.csv', 'nE_pT_sbj04_e2_2.csv', 'nE_pT_sbj05_e2_2.csv', 'nE_pT_sbj09_e2_2.csv', 'nE_pT_sbj10_e2_2.csv')
sprintf('e_%s_e2.Rdata',regmatches(fls,regexpr('sbj\\d{2}',fls)))
[1] "e_sbj01_e2.Rdata" "e_sbj02_e2.Rdata" "e_sbj04_e2.Rdata" "e_sbj05_e2.Rdata" "e_sbj09_e2.Rdata" "e_sbj10_e2.Rdata"
You can easily feed the vector to a function (if possible) or feed the function to the vector with sapply or lapply
fls_new <- sprintf('e_%s_e2.Rdata',regmatches(fls,regexpr('sbj\\d{2}',fls)))
res <- lapply(fls_new,function(x) yourfunction(x))
If I understood correctly, you only change extension from .csv to .Rdata, remove last "_2" and change prefix from "nE_pT" to "e". If yes, this should work:
Output = sub("_2.csv", ".Rdata", sub("nE_pT, "e", file[i]))
I am reading each worksheet of Excel File named "REL" up to worksheet 4 using the repeat function given below. But after reading worksheet for each value of i, I want to save it first in my working directory before reading for i + 1.
i <- 1
repeat {
fcr <- read.xlsx("REL.xlsx", sheet = i, colNames = TRUE)
i <- i + 1
print(i)
if (i > 4) {
break
}
}
In the future please indicate which packages you are using when referencing non-base functions; presumably this is read.xlsx from the xlsx package. To save each worksheet as a csv, you would need to call write.csv(...) after reading the file in, and before the loop begins its next iteration. But you shouldn't even bother with repeat, etc... as above. Use something more idiomatic to R such as sapply:
library(xlsx)
##
list.files()
#[1] "REL.xlsx"
##
sapply(1:4, function(i) {
write.csv(
read.xlsx("REL.xlsx", sheetIndex = i, header = TRUE),
file = sprintf("WS%d.csv", i)
)
})
##
list.files()
#[1] "REL.xlsx" "WS1.csv" "WS2.csv" "WS3.csv" "WS4.csv"
I create a loop like this one:
for (p in 1:nrow(outcomes)) {
id <- apply(regulationtable, 1, function(i)
sum(i[1:length(regulationtable)] != outcomes[p,])==0)
idd <- as.matrix(id)
test2 = subset(idd, idd[,1]==TRUE)
result <- as.data.frame(rownames(test2))
filename = paste("file", p, ".txt")
write.table(result, filename)
}
The results of every loop will be saved as a file. I want to combine this results and create one file with all the results.
Can anyone help me with this?
With the append argument in write.table you can add lines to an existing file rather than overwriting them:
if (p == 1)
{
write.table(result, "file.txt")
} else
{
write.table(result, "file.txt", append = TRUE, col.names = FALSE)
}
Is this what you mean?
EDIT: You might want the first run to initialize it and not append, then each other run to not print the column names ( I do assume these are the same for each table).