Skip to content

Instantly share code, notes, and snippets.

@teeler
Created March 14, 2012 20:06
Show Gist options
  • Save teeler/2039128 to your computer and use it in GitHub Desktop.
Save teeler/2039128 to your computer and use it in GitHub Desktop.
R WTF
# Ok, so appending items to lists.
# I'm fine with this.
f <- list()
f <- c(f, 1)
f <- c(f, 2)
f <- c(f, 3)
# Ok, lets try something fancier, lists of lists.
f <- list()
f <- c(f, list(a=1))
f <- c(f, list(a=2))
f <- c(f, list(a=3))
j <- list(list(a=1), list(a=2), list(a=3))
# I'd expect f == j at this point, but it doesnt, and i dont understand what the hell F is...
@MattNapsAlot
Copy link

You're just getting confused by the syntax.

this:
f <- c(f, list(a=1))
says concatenate the elements of the two lists, both of which are named "a".

this:
j <- list(list(a=1), list(a=2), list(a=3))
says concatenate the three lists, each of which has a single element named "a".

If you want to make j identical to f, you would do this:
j <- list(a=1, a=2, a=3)
which in english is: make a list with three elements, each named "a".

@teeler
Copy link
Author

teeler commented Mar 14, 2012

I want f to be like j, j is the correct one ;)

@MattNapsAlot
Copy link

this is one way to accomplish that:

f <- list()
f[[1]] <- list(a=1)
f[[2]] <- list(a=2)
f[[3]] <- list(a=3)

@teeler
Copy link
Author

teeler commented Mar 14, 2012

I also discovered this:

f <- c(f, list(list(a=1)))
f <- c(f, list(list(a=2)))
f <- c(f, list(list(a=3)))

@MattNapsAlot
Copy link

No surprise there. that's exactly what I'd expect. You keep concatenating the ever-growing list multiple times with itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment