Question

Please correct me if my terminology is wrong because on this question Im not quite sure what Im dealing with regarding elements, objects, lists..I just know its not a data frame. Using the example from prepksel {adehabitatHS} I am trying to modify my own data to fit into their package. Running this command on their example data creates an object? called x which is a list with 3 sections? elements? to it. The example data code:

 library(adehabitatHS)
    data(puechabonsp)
    locs <- puechabonsp$relocs
    map <- puechabonsp$map
    pc <- mcp(locs[,"Name"])
    hr <- hr.rast(pc, map)
    cp <- count.points(locs[,"Name"], map)
     x <- prepksel(map, hr, cp)

looking at the structure of x it is a list of 3 elements called tab, weight, and factor

str(x) 
List of 3
 $ tab   :'data.frame': 191 obs. of  4 variables:
  ..$ Elevation : num [1:191] 141 140 170 160 152 121 104 102 106 103 ...
  ..$ Aspect    : num [1:191] 4 4 4 1 1 1 1 1 4 4 ...
  ..$ Slope     : num [1:191] 20.9 18 17 24 23.9 ...
  ..$ Herbaceous: num [1:191] 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 ...
 $ weight: num [1:191] 1 1 1 1 1 2 2 4 0 1 ...
 $ factor: Factor w/ 4 levels "Brock","Calou",..: 1 1 1 1 1 1 1 1 1 1 ...

for my data, I will create multiple "x" lists and want to merge the data within each segment. So, I have created an "x" for year 2007, 2008 and 2009. Now, I want to append the "tab" element of 08 to 07, then 09 to 07/08. and do the same for the "weight" and "factor" elements of this list "x". How do you bind that data? I thought about using unlist on each segment of the list and then appending and then joining the yearly data for each segment and then rejoining the three segments back into one list. But this was cumbersome and seemed rather inefficient.

I know this is not how it will work, but in my head this is what I should be doing:

newlist<-append(x07$tab, x08$tab, x09$tab)
newlist<-append(x07$weight, x08$weight, x09$weight)
newlist<-append(x07$factor, x08$factor, x09$factor)

maybe rbind? do.call("rbind", lapply(....uh...stuck

Was it helpful?

Solution

append works for vectors and lists, but won't give the output you want for data frames, the elements in your list (and they are lists) are of different types. Something like

tocomb <- list(x07,x08,x09)
newlist <- list(
  tab = do.call("rbind",lapply(tocomb,function(x) x$tab)), 
  weight = c(lapply(tocomb,function(x) x$weight),recursive=TRUE), 
  factor = c(lapply(tocomb,function(x) x$factor),recursive=TRUE)
)

You may need to be careful with factors if they have different levels - something like as.character on the factors before converting them back with as.factor.

This isn't tested, so some assembly may be required. I'm not an R wizard, and this may not be the best answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top