Reputation: 222
Is there a way of defining a list-as-observation inside the loop? For instance, I could just run the following code to replace each list-as-observation whenever another observation of a data.frame meets a certain condition, like in the code below, but I need to create the lists
as a set of NULL
lists
before running the loop. Also, I haven't figured out how to place the list
in the line that creates the data.frame
-- is there way to do this?
Here it is the code:
#line that creates the data.frame: I wished to know how to place the list
#(at the line after creating the data.frame object) inside the data.frame function.
df = data.frame(x=1:10)
#line that creates the list as NULL values before replacing them in the loop
df$y = list(c())
#random replacement condition
df$z = c(0,0,1,0,1,0,1,0,0,0)
#Loop: could I create the list variable on the run without creating it before the loop?
for(i in 1:10) {
if (df$z[i]==1) {
df$y[i] = list(c("a","b"))
}
}
If there is a more state of the art or a recommend way of doing this following some set of principles (e.g. tidy) I would be glad if someone could refer to it.
Upvotes: 0
Views: 41
Reputation: 389165
I am not sure why you want to do this but you can reduce your code to
df <- data.frame(x = 1:10, z = c(0,0,1,0,1,0,1,0,0,0))
df$y <- ifelse(df$z == 1, list(c("a","b")), list())
and it would give the same result.
Upvotes: 1