Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent names in dataframe list from disappearing

Tags:

list

dataframe

r

So I initialize a list, which I want to fill with dataframes:

listz <- vector("list",2)

I also want to keep the dataframes' names around, so I assign them:

listzNames <- c("frame1","frame2")
names(listz) <- listzNames

The problem is, with every reassignment I make to the dataframes, the names go NULL:

listz <- list(data.frame("id" = 1:3, "hat" = 1:3),
           data.frame("id" = 4:6, "hat" = 4:6))

> names(listz)
NULL

I know why this happens, but what would be a neat alternative to reassigning the names at every dataframe reassignment?

like image 473
dmvianna Avatar asked Aug 30 '12 23:08

dmvianna


2 Answers

When you assign

listz <- list(data.frame("id" = 1:3, "hat" = 1:3),
           data.frame("id" = 4:6, "hat" = 4:6))

You are replacing the object formerly defined as listz, it is a new object, unrelated to any previous objects of that name.

Therefore is no need to initialize the list in this case

you have (at least) four options for setting names of a list

option 1 - setNames

# Option 1 - using setNames
listz <- setNames(list(data.frame("id" = 1:3, "hat" = 1:3),
           data.frame("id" = 4:6, "hat" = 4:6)), listzNames)

option 2 - name as you go

# Option 2 - naming the list as you go
listz <- list(frame1 = data.frame("id" = 1:3, "hat" = 1:3),
           frame2 = data.frame("id" = 4:6, "hat" = 4:6))

option 3 - Hmisc and llist

# If your data.frames already exist
# use the llist function in Hmisc, which names the list
# using the names of the object in each element
library(Hmisc)
frame1 <- data.frame("id" = 1:3, "hat" = 1:3)
frame2 <- data.frame("id" = 4:6, "hat" = 4:6)

listz <- llist(frame1,frame2)

option 4 - prexisting using setNames and get

# if your data.frames already exist in the global environment then
# you can use
listz <- setNames(lapply(listzNames, get),listzNames)

option 5 initializing the list (I don't like this)

listz <- vector("list",2)
names(listz) <- listzNames
listz[[1]] <- data.frame("id" = 1:3, "hat" = 1:3)
listz[[2]] <- data.frame("id" = 4:6, "hat" = 4:6)

I don't like this option, it requires more typing and therefore more chance of errors!

Note about lapply

lapply will preserve any names

lapply(listz,head,n=1)

#$frame1
#  id hat
#1  1   1
#
#$frame2
#  id hat
#1  4   4
like image 180
mnel Avatar answered Oct 25 '22 10:10

mnel


Option 6 :)

listz[] <- list(data.frame("id" = 1:3, "hat" = 1:3),
                data.frame("id" = 4:6, "hat" = 4:6))
like image 27
Charles Avatar answered Oct 25 '22 10:10

Charles