Home > front end >  R - Given a List of Vectors replace values in Vectors for each Vector with LOOP
R - Given a List of Vectors replace values in Vectors for each Vector with LOOP

Time:01-23

Here is the set up. I have vec1 containing 5 numbers. I also have h5-h9 as a vector of 800 elements. The knot_list is a list of h5-h9 vectors containing 800 0's per h vector. Given x, I want to replace each h5,h6,h7,h8,h9's 800 elements with the formula x-(vec[i]) where i is 1:5 in this case.

vec1 <- c(1, 2, 3,4,5)
vec1 <- list(vec1) # needed for my real code
h5=rep(0,800);h6=h5;h7=h5;h8=h5;h9=h5
list_knot<- list(h5,h6,h7,h8,h9)
list_length <- length(list_knot) # 5 
x=seq(from=1,to=800,length.out=800)

Is there a way to make the formula described above replace each vector value in each element of the list? I tried doing for loops, but syntax is wrong.

for (i in 1:list_length){
  print(i)
  for (j in 1:length(seq(0,800))){
  list_knot[[i]][[j]] = x-vec1[[1]][[i]]^3
  }
 
}

The list_knot is set up where it is a list containing 5 vectors. Each vector has 800 0's that need to be replaced by the formula. How can I do this?

CodePudding user response:

It seems to me that this is what you are looking for

vec1 <- list(c(1, 2, 3, 4, 5)) # as per your requirement
list_knot <- lapply(vec1[[1]], function(v, x) x - v^3, x = 1:800)

, i.e., subtract each element of vec1 from the same x (1:800) and return a list of vectors. As you would like to replace every single element for each h in list_knot, you might just drop that list completely and reconstruct a new one.

  •  Tags:  
  • Related