A.Birdman
A.Birdman

Reputation: 171

Add different length elements to a list in R

I've created an empty list which I need to populate with names from a dataframe. If I have a single name, it runs fine, but if there are multiple names, it throws the error: " number of items to replace is not a multiple of replacement length"

I get that it means I've got 2 or more items I'm trying to put into the list element, but according to everything I read on lists, "you can store anything in a list". So I know I'm doing something boneheaded but I can't figure out how to get where I need to go.

df <- structure(list(V1 = c("50.strata1", "50.strata1+strata2", "50.strata2* strata4"), 
V2 = c("strata1.50", "strata1.50", "strata2.50"), V3 = c(NA, "strata2.50", "strata4.50"), V4 = c(NA, NA, "st2st4.50")), 
.Names = c("V1", "V2", "V3", "V4"), row.names = c(1L, 2L, 3L), class = "data.frame")

mlist <- vector("list",nrow(df))    # create the list
names(mlist) <- df[,1]              # name the elements because I'll need to be able to call them intuitively later

for(i in 1:nrow(df)){               
x1 = unname(unlist(df[i,2:4]))  # pull the last three columns of the dataframe
x2 = x1[!is.na(x1)]             # strip NA so only left with names
mlist[i] = x2                   # add to the empty list element
}

What am I missing that will allow me to add the variable number of names to the list? Once I have the list built, I'll need to use each element iteratively in another operation, beginning by counting the names within a given element.

Upvotes: 0

Views: 746

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

Change mlist[i] = x2 to mlist[[i]] = x2. In a list, [ is a sublist, whereas [[ is a single element.


Another way to get the same result:

mlist2 = apply(df[, 2:4], 1, function(x) unname(x[!is.na(x)]))
names(mlist2) = df[, 1]

Upvotes: 2

Related Questions