I am trying to generate attribute tables for a bunch of rasters using the 'levels' function in the raster package. I have all of my rasters in a list, with their corresponding attribute tables as data frames in a separate list. I can not find a method which will take the first raster in the list, give it the attributes of the first df in the list of dfs.
require(raster)
## Generate test rasters with values
rast1<-raster(ncol=10, nrow=10, xmn=0, xmx=10, ymn=0, ymx=10)
values(rast1)<-round(runif(100,1,4))
rast2<-raster(ncol=11, nrow=10, xmn=0, xmx=10, ymn=0, ymx=10)
values(rast2)<-round(runif(110,1,4))
testrastlist<-list(rast1, rast2)
## Generate test data frames for attribute tables
df1<-data.frame('ID'=c(1,2,3,4),'a'=c(1,2,3,4), 'b'=c(1,2,3,4), 'c'=c(1,2,3,4))
df2<- data.frame('ID'=c(1,2,3,4),'d'=c(5,6,7,8),'e'=c(5,6,7,8),'f'=c(5,6,7,8))
testdflist<-list(df1,df2)
I have tried the method below: which does not work,
levels(testrastlist)<-testdflist
Although this works for a single raster and single data frame:
#This works
levels(rast1)<-df1
# As does this
levels(testrastlist[[1]]<-testdflist[[1]]
I would prefer an apply
solution if there is one, but I haven't been able to get lapply
or Map()
to work either I have not had luck using a for loop either.
I think the solution is structured something along these lines: (taken directly from applying a function on two lists) but I am unsure how to restructure it for my purposes. Any suggestions?
mapply(function(X,Y) {
lapply(1:10, function(row) cor(X[row,], Y[row,]))
}, X=listA, Y=listB)