Using list to write values - r

I want to write values into an R list. For this I have created a test program:
testWriteToList <- function() {
for (i in seq(1:10)) {
x <- i
y <- i+1
list <- list(c(x,y))
}
return(list)
}
(testWriteToList())
However, as output I get:
[[1]]
[1] 10 11
In fact, I want all the ouput in a list. How to do that?
I appreciate your answer!!!

You can change your entire loop to lapply
lapply(1:10, function(i) c(i, i+1))

Related

Apply a function to objects in my global environment R

This code chunk creates a 10 objects based of length of alpha.
alpha <- seq(.1,1,by=.1)
for (i in 1:length(alpha)){
assign(paste0("list_ts_ses_tune", i),NULL)
}
How do I put each function into the new list_ts_ses_tune1 ... null objects I've created? Each function puts in a list, and works if I set list_ts_ses_tune1 <- lapply ...
for (i in 1:length(alpha))
{
list_ts_ses_tune[i] <- lapply(list_ts, function(x)
forecast::forecast(ses(x,h=24,alpha=alpha[i])))
list_ts_ses_tune[i] <- lapply(list_ts_ses_tune[i], "[", c("mean"))
}
Maybe this is a better way to do this? I need each individual output in a list of values.
Edit:
for (i in 1:length(alpha))
{
list_ts_ses_tune[[i]] <- lapply(list_ts[1:(length(list_ts)/2)],
function(x)
forecast::forecast(ses(x,h=24,alpha=alpha[i])))
list_ts_ses_tune[[i]] <- lapply(list_ts_ses_tune[[i]], "[", c("mean"))
}
We can use mget to return all the objects into a list
mget(ls(pattern = '^list_ts_ses_tune\\d+'))
Also, the NULL list can be created more easily instead of 10 objects in the global environment
list_ts_ses_tune <- vector('list', length(alpha))
Now, we can just use the OP's code
for (i in 1:length(alpha))
{
list_ts_ses_tune[[i]] <- lapply(list_ts, function(x)
forecast::forecast(ses(x,h=24,alpha=alpha[i])))
}
If we want to create a single data.frame
for(i in seq_along(alpha)) {
list_ts_ses_tune[[i]] <- data.frame(Mean = do.call(rbind, lapply(list_ts, function(x)
forecast::forecast(ses(x,h=24,alpha=alpha[i]))$mean)))
}
You could simply accomplish everything by doing:
library(forecast)
list_ts_ses_tune <- Map(function(x)
lapply(alpha, function(y)forecast(ses(x,h=24,alpha=y))['mean']), list_ts)

Including an index inside a paste-command while running a loop in R

I want to assign a value to pre-defined lists using an index in a paste-command while running a loop in R.
I always get an error that the target of assignment expands to non-language objects.
Here is an example:
List_1 <- List_2 <- list()
for(i in 1:2){
paste("List_", i, sep="")[[i]] <- i
}
The expected output can be generated by:
List_1[[1]] <- 1; List_1[[2]] <- 2
List_2[[1]] <- 1; List_2[[2]] <- 2
A more 'R' way might be:
List_12 <- as.list(1:2)
for(i in 1:2){
for(j in 1:2){
List_12[[i]][[j]] <- i
}
}
You can name your lists within that structure:
names(List_12) <- paste0("List_",c(1,2))
Then you can index by name:
List_12[["List_1"]]
I'm not clear about why each list should have only zeros. However, assigning items to pasted names is a headache in R. You have to use the assign function, and specify the environment. Something like this.
for(i in 1:2){
values <- list(1:i)
assign(x = paste0("List_", i), value = values, envir = globalenv())
}
List_1
[[1]]
[1] 1
List_2
[[1]]
[1] 1 2

Putting user-defined on a list in for loop

I have problems storing user defined functions in R list when they are put on it in a for loop.
I have to define some segment-specific functions based on some parameters, so I create functions and put them on a list looping through segments with for-loop. The problem is I get same function everywhere on a result list.
The code looks like this:
n <- 100
segmenty <- 1:n
segment_functions <- list()
for (i in segmenty){
segment_functions[[i]] <- function(){return(i)}
}
When i run the code what I get is the same function (last created in the loop) for all indexes:
## for all k
segment_functions[[k]]()
[1] 100
There is no problem when I put the functions on list manually e.g.
segment_functions[[1]] <- function(){return(1)}
segment_functions[[2]] <- function(){return(2)}
segment_functions[[3]] <- function(){return(3)}
works just fine.
I honsetly have no idea what's wrong. Could you help?
You need to use the force function to ensure that the evaluation of i is done during the assignment into the list:
n <- 100
segmenty <- 1:n
segment_functions <- list()
f <- function(i) { force(i); function() return(i) }
for (i in segmenty){
segment_functions[[i]] <- f(i)
}
I'd use lapply and capture i in a clousre of the wrapper:
segment_functions <- lapply(1:100, function(i) function() i)

R programming: save three dimensional outputs after loop

I am new to R and I would like to save the out puts after the loop
for (i in 1:5) {
for (d in 1:10) {
fonction1
fonction2
fonction3
}
}
At the end I would like to have 1 list-> contains 5 list-> contains 1*10 data frame -> contains certain number*3 numeric data. (I dont know if im saying it correctly, what i want to have is: like in Matlab, there is a 1*5 structure -> contains five 1*10 structure -> contain certain number*3 numeric data).
thanks in advance
Looks like you are looking after something like the following:
out <- list()
for (i in 1:5) {
outList <- list()
for (d in 1:10) {
outVect <- c()
outVect[1] <- fonction1()
outVect[2] <- fonction2()
outVect[3] <- fonction3()
outList[[d]] <- outVect
}
out[[i]] <- outList
}
Then you can look at:
str(out)
to see the structure of your answer
Try this:
lst <- lapply(1:5, function(i) {
lapply(1:10, function(d) {
data.frame(function1(),
function2(),
function3())
})
})
Assuming function1, function2 and function3 all return equal-length vectors, the above code should produce your desired object. You can use i and d identically as you would have used them in your for loop code.

*apply in r to repeat a function

I've written a function that is a simulation, that outputs a vector of 100 elements, and I want to use the *apply functions to run the function many times and store the repeated output in a new vector for each time the simulation is run.
The function looks like:
J <- c(1:100)
species_richness <- function(J){
a <- table(J)
return(NROW(a))
}
simulation <- function(J,gens,ploton=FALSE,v=0.1){
species_richness_output <- rep(NA,gens)
for(rep in 1:gens){
index1 <- sample(1:length(J),1)
if(runif(1,0,1) < v){
J[index1] <- (rep+100)
}
else{
index2 <- sample(1:length(J),1)
while(index1==index2) {
index2 <- sample(1:length(J),1)
}
J[index1] <- J[index2]
}
species_richness_output[rep] <- species_richness(J)
}
species_abundance <- function(J){
a <- table(J)
return(a)
}
abuntable <- species_abundance(J)
print(abuntable)
octaves <- function(abuntable){
oct <- (rep(0,log2(sum(abuntable))))
for(i in 1:length(abuntable)){
oct2 <- floor(log2(abuntable[i])+1)
oct[oct2] <- oct[oct2]+1
}
print(oct)
}
# octaves(c(100,64,63,5,4,3,2,2,1,1,1,1))
if(ploton==TRUE){
hist(octaves(abuntable))
}
print(species_richness(J))
return(J)
}
simulation(J, 10000,TRUE,v=0.1)
So that's my function, it takes J a vector I defined earlier, manipulates it, then returns:
the newly simulated vector J of 100 elements
a function called octave that categorises the new vector
a histogram corresponding to the above "octave"
I have tried a number of variations: using lapply, mapply
putting args=args_from_original_simulation
simulation_repeated <- c(mapply(list, FUN=simulation(args),times=10000))
but I keep getting an error with the match.fun part of the mapply function
Error in match.fun(FUN) :
'simulation(J, 10000, FALSE, 0.1)' is not a function, character or symbol
This is despite the simulation I have written showing as being saved as a function in the workspace.
Does anyone know what this error is pointing to?
In this line:
simulation_repeated <- c(mapply(list, FUN=simulation(args),times=10000))
You are not giving a function to mapply. You are (essentially) passing the result of calling simulation(args) and simulation does not return a function.

Resources