0

I have a loop and I am trying to create a new column to a list of lists with a constant number that is dependent on the value j (j is a number from 1 to 12). The rest of the loop works and the previous line renames the columns of the same dataframe.

for(i in 1:length(idw.list)){
  idw.output[[i]] <- list()
  for(j in 1:length(idw.list[[i]])){
    idw.output[[i]][[j]]= as.data.frame(idw.list[[i]][[j]]) 
    names(idw.output[[i]][[j]])[1:3] <- c("LON", "LAT", "MAXMEAN")
    (idw.output[[i]][[j]])[, "MONTH"] = j
}
}

I have tried this:

(idw.output[[i]][[j]])[, "MONTH"] = j

which leads to this error:

Error in (idw.output[[i]][[j]]) <- `*vtmp*` : 
  could not find function "(<-"

Right now the data looks like this:


    LON          LAT        MAXMEAN
1   11.66847    -18.04208   30.07742    
2   11.76847    -18.04208   30.07742    
3   11.86847    -18.04208   30.07742

and i would like to add the column, so that in the case j=1 (first loop):

    LON          LAT        MAXMEAN    MONTH
1   11.66847    -18.04208   30.07742    1
2   11.76847    -18.04208   30.07742    1
3   11.86847    -18.04208   30.07742    1

I would appreciate any help, thank you!

3
  • 1
    Probably there is a better way to do this. It would be helpful if you could share a reproducible example along with expected output. Commented Sep 15, 2019 at 13:29
  • 1
    Convert (idw.output[[i]][[j]])[, "MONTH"] = j to idw.output[[i]][[j]][, "MONTH"] = j. (Parenthesis are gone). Also this is quite horrible practice. I suggest creating a small example for example 2 idenical data.frames with 3 observations, with the expected result. Likely this will yield an answer with better code. Commented Sep 15, 2019 at 13:49
  • Thanks! It worked and I will change the code. Commented Sep 15, 2019 at 13:57

1 Answer 1

1

The post isn't really reproducible and this is too long for a comment but maybe you can try

for(i in seq_along(idw.list)) {
   for(j in seq_along(idw.list[[i]])) {
       names(idw.list[[i]][[j]])[1:3] <- c("LON", "LAT", "MAXMEAN")
       idw.list[[i]][[j]]["Month"] = j
     }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.