0

My R skill is still at infancy and I am trying to loop over a calculation but I am not getting the right solution.

I want to perform the following operating 30 times

l1 = kak[dat1[[1]]$d1,dat1[[1]]$d2,tl] #1
l2 = kak[dat1[[2]]$d1,dat1[[2]]$d2,tl] #2
................................
l30 = kak[dat1[[30]]$d1,dat1[[30]]$d2,tl] #30
# then cbind each
cbind(l1,l2,...,l30)

In each case [[i]] must assume same value. Instead of doing it 30 times I decided to write a function which doesn't seem to work.

Here is function I tried writing:

dat1 <- split(dat,dat$group) ##group runs from 1:30
#dat has three column group, d1 and d2. d1 and d2 are numeric
nw <- 0
for(i in 1:length(dat1)){
# str(kak) num [1:360, 1:180, 1:830] 
# str(tl) int [1:84] 754 ...
nw =kak[dat1[[i]]$d1,dat1[[i]]$d2,tl] 
} 

I tried searching for similar question here had no luck. Anyone with solution or an idea of an exiting thread that solved similar issue should kindly point me in the right direction.

moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
  • You just want to loop over a list? What about `lapply`? – divibisan Mar 20 '19 at 15:58
  • I assumed you had made a typo and changed your `$2` into `$d2` – moodymudskipper Mar 20 '19 at 16:00
  • 1
    `kak[dat1[[1]]$d1, dat1[[1]]$d2 ,tl]` makes sense only if `tl` is meant to be passed to the `drop` argument of `[`, I'm not sure that's what you want to do. You might want to provide us a reproducible example, here's a great link : https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – moodymudskipper Mar 20 '19 at 16:02
  • I am trying to follow this exercise https://cran.r-project.org/web/packages/futureheatwaves/vignettes/starting_from_netcdf.html. I am trying to implement the code in this link but instead of a specific location at a time I am trying to do thirty locations at a time. This is the exact part of the code that I am trying to implement in a loop lon_index <- which.min(abs(lon - 116.4)) lat_index <- which.min(abs(lat - 39.9)) time_index <- which(format(tas_time, "%Y-%m-%d") == "2075-07-15") tas[lon_index, lat_index, time_index] – user234526 Mar 20 '19 at 16:07

0 Answers0