Writing functions

Hey :slight_smile:
I have a list "d_list" with 12 elements. Every element contains 24 entries of the type "double [450]". Two of this entries are called "Time" and "P1mean".

I worte a little program to modify some entries of "P1mean":

xs <- c(225,261,294,343,371,398,435)
xe <- c(228,265,296,349,373,406,439)
diff <- xe-xs-1
l_x <- list()
l_y <- list()
for(i in 1:length(xs)){l_x[[i]] <- c(d_list[[1]]$Time[xs[i]],d_list[[1]]$Time[xe[i]])}
for(i in 1:length(xs)){l_y[[i]] <- c(d_list[[1]]$P1mean[xs[i]],d_list[[1]]$P1mean[xe[i]])}
for(i in 1:length(xs)){for(k in 1:diff[i]){(approx(l_x[[i]],l_y[[i]],xout=d_list[[1]]$Time[xs[i]+k]))$y -> d_list[[1]]$P1mean[xs[i]+k]}}

This works fine. I have to do the same thing to some other Elements of the list d_list, so i defined the following function:

inter <- function(l,v1,v2,z){
  diff <- v2-v1-1
  l_x <- list()
  l_y <- list()
  for(i in 1:length(v1)){l_x[[i]] <- c(l[[z]]$Time[v1[i]],l[[z]]$Time[v2[i]])}
  for(i in 1:length(v1)){l_y[[i]] <- c(l[[z]]$P1mean[v1[i]],l[[z]]$P1mean[v2[i]])}
  for(i in 1:length(v1)){for(k in 1:diff[i]){l[[z]]$P1mean[v1[i]+k] <- (approx(l_x[[i]],l_y[[i]],xout=l[[z]]$Time[v1[i]+k]))$y}}
  }

If I write the following command:

inter(d_list, c(225,261,294,343,371,398,435), c(228,265,296,349,373,406,439), 1)

which should do the same thing as the first r chunk, it doesn't work.
Does anyone see my mistake?

Thank you!

If I understand your code correctly, you need to return the value of l from the function and assign that to d_list.

inter <- function(l,v1,v2,z){
  diff <- v2-v1-1
  l_x <- list()
  l_y <- list()
  for(i in 1:length(v1)){l_x[[i]] <- c(l[[z]]$Time[v1[i]],l[[z]]$Time[v2[i]])}
  for(i in 1:length(v1)){l_y[[i]] <- c(l[[z]]$P1mean[v1[i]],l[[z]]$P1mean[v2[i]])}
  for(i in 1:length(v1)){
      for(k in 1:diff[i]){
         l[[z]]$P1mean[v1[i]+k] <- (approx(l_x[[i]],l_y[[i]],xout=l[[z]]$Time[v1[i]+k]))$y
      }
  }
  return(l)
}

d_list <- inter(d_list, c(225,261,294,343,371,398,435), c(228,265,296,349,373,406,439), 1)

When you pass d_list to the argument l in inter(), the changes made to l within the function do not affect the value of d_list outside the function.

Thank you! Now it works wonderfully :wink:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.