tdsmith / aRrgh

A newcomer's (angry) guide to data types in R
Other
307 stars 14 forks source link

No way to append a list in place? Wtf #22

Open ifly6 opened 6 years ago

ifly6 commented 6 years ago

In Java, I have a list (lets say implementation is ArrayList). It's a happy list. And you can add things do that list, because lists are not arrays and you might some time want to add something to it.

List<Integer> ints = new ArrayList<>();
ints.add(1); // works

In Python, I too can have a list. And it's a happy list. You too can add things do this list, because you might want to do that some time. So in our world, where we have a number of data files, the number of which might not be pre-established (something of a reasonable and common use-case), we can do this:

dfs = []
for file in files:
    df = df_supplier(file)  # eg -- pandas.read_csv(file)
    dfs.append(df)

You want to that in R? You're out of luck. The easiest way I can find to do this is to get yourself the package rlist and then do this:

library(rlist)
dfs = list()
for i : 1:length(files) {
    file = files[[i]]
    dfs = list.append(dfs, read_XYZ(file, arguments...))
}

This way, you can have the privilege of wasting your computer time and hard-earnt electricity copying data you already have to a location in which it already is. This is pRogRess! But if you don't want to install a whole library just do this, do not be afraid!

Just write yourself a function,

append = function(li, obj) {
    name <- deparse(substitute(li))
    li[[length(li) + 1]] = obj
    assign(name, li, envir=parent.frame())
    return()
}

Now, with the power of R, you can pass your list, have the whole thing deparsed, add a single thing to the end of the list, and then manually assign that whole thing back to the parent environment's entry of the list. Fortunately, you still have the glorious featuRe of wasting your computer time and hard-earnt electricity copying data you already have to a location in which it already is! Efficiency! (The word efficiency has no Rs in it, that's how you know it's efficient.)

dwinsemius commented 4 years ago

There is already an append function in base R. Look it up. It can do what you desire as well as insert values into the middle of lists. (Note that lists are vectors, so do not make the incorrect conclusion that this only applies to atomic vectors.)

The requirement that it be done "in place" is simply not an R feature. R is a functional language. If you don't like it, then use a different tool.