[R] Lists with NULL entries

Peter Langfelder peter.langfelder at gmail.com
Tue Sep 21 04:06:45 CEST 2010


Hello,

I encountered a weird problem. Consider the following code that takes
a list "lst" and shifts all elements one index up (for example, to
make space for a new first element):

lst = list(1,2)
ll = length(lst);
for (i in ll:1)
   lst[[i+1]] = lst[[i]];
lst

If you run it, you get the expected result

[[1]]
[1] 1

[[2]]
[1] 1

[[3]]
[1] 2

Now I change the input such that the first element is a NULL.

lst = list(NULL,2)
ll = length(lst);
for (i in ll:1)
   lst[[i+1]] = lst[[i]];
lst

When you run the code, you get

[[1]]
NULL

[[2]]
[1] 2

i.e. the shift did not happen. Why is that and how can the shift be
made to work correctly in the presence of NULL elements in the list?

Thanks,

Peter



More information about the R-help mailing list