If foo <- list()
, I find myself writing foo[[length(foo)+1]] <- bar
a lot when really I just want to write push(foo, bar)
.
Similarly (though much less frequently) bar <- foo[[length(foo)]]
would be much nicer as bar <- pop(foo)
.
It's the repetition of the variable name that kills me. Consider:
anInformative.selfDocumenting.listName[[length(anInformative.selfDocumenting.listName)+1]] <- bar
edit:
foo <- append(foo, bar)
doesn't work for me
foo <- list()
for (i in 1:10) {
x <- data.frame(a=i, b=rnorm(1,0,1))
foo[[length(foo)+1]] <- x
}
str(foo)
Gives a list of 10 objects as expected.
foo <- list()
for (i in 1:10) {
x <- data.frame(a=i, b=rnorm(1,0,1))
foo <- append(foo, x)
}
str(foo)
Gives a list of 20 objects.
foo[[length(foo)+1]] <- bar
could be rewritten as
foo <- append(foo, bar)
and
bar <- foo[[length(foo)]]
could be rewritten as
bar <- tail(foo,1)
Note that with functional languages such as R functions generally aren't supposed to changes values of parameters passed to them; typically you return a new object which you can assign elsewhere. The function should have no "side effects." Functions like push/pop
in other languages usually modify one of the passed parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With