Saving loop results R - r

Please tell me how can I save my loop results into the table(data.frame) or even .csv file. I can't handle with that issue by myself.
for (i in 1:10000){
x<-pois(1,40)
sum<-round(digits = 2, sum(rlnorm(x, log(10), log(5))))
}

If you want to use a for loop, create an empty vector and then iterate through each position.
mySums <- numeric(10000)
for (i in 1:10000){
x <- rpois(1,40)
mySums[i] <- round(digits = 2, sum(rlnorm(x, log(10), log(5))))
}
It is straightforward to then turn this into a dataframe or any other format you require.
Edit: This is assuming you meant to use rpois() or something similar.

Assuming that you want to call rpois() (and not pois()):
mySums <- replicate(10000, round(digits=2, sum(rlnorm(rpois(1,40), log(10), log(5)))))

yes indeed, I meant rpois function. I solved it using the next formula:
Results=matrix(0,10000,1)
for ( i in 1:10000)
{
x<-rpois(1,40)
Results[i,1]<-round(digits = 2, sum(rlnorm(x,log(20), log(4))))
}

Related

R - Saving the values from a For loop in a vector or list

I'm trying to save each iteration of this for loop in a vector.
for (i in 1:177) {
a <- geomean(er1$CW[1:i])
}
Basically, I have a list of 177 values and I'd like the script to find the cumulative geometric mean of the list going one by one. Right now it will only give me the final value, it won't save each loop iteration as a separate value in a list or vector.
The reason your code does not work is that the object ais overwritten in each iteration. The following code for instance does what precisely what you desire:
a <- c()
for(i in 1:177){
a[i] <- geomean(er1$CW[1:i])
}
Alternatively, this would work as well:
for(i in 1:177){
if(i != 1){
a <- rbind(a, geomean(er1$CW[1:i]))
}
if(i == 1){
a <- geomean(er1$CW[1:i])
}
}
I started down a similar path with rbind as #nate_edwinton did, but couldn't figure it out. I did however come up with something effective. Hmmmm, geo_mean. Cool. Coerce back to a list.
MyNums <- data.frame(x=(1:177))
a <- data.frame(x=integer())
for(i in 1:177){
a[i,1] <- geomean(MyNums$x[1:i])
}
a<-as.list(a)
you can try to define the variable that can save the result first
b <- c()
for (i in 1:177) {
a <- geomean(er1$CW[1:i])
b <- c(b,a)
}

How to show replicate number when using sapply in R?

Consider the function below:
f = function(i) i^2
Now we find the output of f for an input vector of length 1000 (or equivalently to run f for 1000 replications) by:
output = c()
for (i in 1:1000) output[i] = f(i)
In the case of running time-consuming functions, we might like to know which replication we are. So we can use:
output = c()
for (i in 1:1000) {output[i] = f(i); cat("Replicate=", i, "\n")}
This gives the replicate number at the end of each replication. Now what if we use sapply instead of for:
output = sapply(1:1000, function(i) f(i))
How can we see which replicate we are while using sapply? Note that I tried adding cat("Replicate=", i, "\n") in the definition of f. This shows the replicate number, but only at the end of the entire run and not at the end of each replicate.
you say you have tried it, but this code works just great for me:
result <- sapply(1:1000, function(x) {
print(x) # cat works too
return(x^2)
})
You may have forgotten the curly brackets! :-)

R_ How to put a variable in a name

I have 50 files to read in R and I created this loop to help me. I would like to know if it is possible to do something like this in R.
How can I write it properly in R?
library(foreign)
for(i in 1:50 ){
tpi <- read.dbf('toto_%i%')
}
Help please.
We can do this using lapply
lst <- lapply(1:50, function(i) read.dbf(paste0("toto_", i)))
You want to use the function paste. As written your loop will overwrite tpi everytime it increments, so you will want to use a list to store the data.
toto = list()
for(i in 1:50)
{
toto[i] = read.dbf(paste0("toto_", i))
}
A shortcut using lapply gets the same results:
toto = lapply(1:50, function(x) read.dbf(paste0("toto_", x)))

splitting a list and writing multiple files with R - plyr?

I'm breaking my head on how to write multiple files from each row of the input matrix, after some calculations. The code that I'm using now looks like this:
akl <- function(dii) {
ddi <- as.matrix(dii)
m <- rowMeans(ddi)
M <- mean(m) # mean(ddi) == mean(m)
r <- sweep(ddi, 1, m)
b <- sweep(r, 2, m)
return(b + M)
}
require(plyr)
akl.list <- llply(1:nrow(aa), function(i) {
akl(dist(aa[i, ]))
})
The akl.list that I create is too large for large input matrix and I cannot store it in the RAM. My idea was to write on files each matrix that I obtain in the llply loop. Is there an easy way to do that?
thank you!!
gibbi
you can use do_ply since you want just the loop feature
d_ply(aa, 1,function(row){
a <- akl(dist(row))
write.table(a) ## you save in a file here
},.progress='text' ## to show progress (optional)
)

R checking a parameter is defined

I'm looking for a general practice how to check a parameter was defined in a function.
I came up with these three ideas. Which one is the proper way of doing it?
Unfortunately, the third one is not working. substitute() is working differently in a function and I couldn't figure it out how to use it properly.
file.names <- list(
cov.value <- "cov.rds",
plot.name <- "plot.pdf"
)
test1 <- function(file.names){
is.save <- !missing(file.names)
}
test2 <- function(file.names = NULL) {
is.save <- !is.null(file.names)
}
test3 <- function(file.names = NULL) {
is.save <- exists(as.character(substitute(file.names)))
}
I personally think the second approach with a default value is MUCH easier to use & understand. (And the third approach is just really bad)
...especially when you are writing a wrapper function that needs to pass an argument to it. How to pass a "missing"-value is not obvious!
wraptest1 <- function(n) {
file.names <- if (n > 0) sample(LETTERS, n)
else alist(a=)[[1]] # Hacky way of assigning 'missing'-value
print(test1(file.names))
}
wraptest1(2) # TRUE
wraptest1(0) # FALSE
wraptest2 <- function(n) {
file.names <- if (n > 0) sample(LETTERS, n)
else NULL # Much easier to read & understand
print(test2(file.names))
}
wraptest2(2) # TRUE
wraptest2(0) # FALSE
[granted, there are other ways to work around passing the missing value, but the point is that using a default value is much easier...]
Some default values to consider are NULL, NA, numeric(0), ''
It's generally a good idea to look at code from experienced coders---and R itself has plenty of examples in the R sources.
I have seen both your first and second example being used. The first one is pretty idiomatic; I personally still use the second more often by force of habit. The third one I find too obscure.

Resources