4

I know that for loops can be avoided almost all the time in R if you understand the language properly, but I'm struggling to find out the clever way of doing this

for (i in 1:100){
  AllData[[i]]$Div = NULL
}

Where AllData is a list of 100 lists of various sizes. Can someone clue me in?

1 Answer 1

5

Like this:

AllData <- lapply(AllData, `[[<-`, "Div", NULL)
Sign up to request clarification or add additional context in comments.

8 Comments

Isn't it possible without lapply?
What's wrong with it? It seems appropriate since you are working with a list.
There's nothing wrong, but it doesn't really further my understanding that much because it's so equivalent to my code. I might be looking for something that doesn't exist though, as I was expecting something like AllData[[1:100]] = NULL
I don't think you can, but let's wait and see. Also note that your AllData[[1:100]] = NULL does not mention Div.
There is no increase in readability with a for loop unless you cannot read R. A big purpose of apply is expressiveness and avoiding the typical tendency to write long for loops. Just thinking of doing each step separately with a separate apply often provides performance boosts because somewhere in there you can get in a vectorized operation.
|

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.