Let's say I have a list of data.frames
:
假设我有一个data.frames列表:
a1<-as.data.frame(1:9)
a2<-as.data.frame(2:10)
a3<-as.data.frame(3:11)
a.list<-list(a1,a2,a3)
Now I want to convert each data.frame of the list into a 3 by 3 raster
layer. The layers should be in a list afterwards.
现在我想将列表的每个data.frame转换为3乘3的栅格图层。之后,图层应该在列表中。
I tried to perform this with lapply
, but can't really tell what the problem is:
我尝试用lapply执行此操作,但无法确定问题是什么:
r.list<-lapply(a.list, raster(nrows=3, ncols=3))
2 个解决方案
#1
1
You probably need to convert your dataframes to matrices first. Exploit the fact that you have 1-column data frames to convert them to vectors and then use the matrix
function:
您可能需要先将数据帧转换为矩阵。利用以下事实:您有1列数据帧将它们转换为向量,然后使用矩阵函数:
> rl = lapply(a.list, function(X) raster(matrix(X[,1],nrow=3)))
> rl[[1]]
class : RasterLayer
dimensions : 3, 3, 9 (nrow, ncol, ncell)
resolution : 0.3333333, 0.3333333 (x, y)
extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : in memory
names : layer
values : 1, 9 (min, max)
You may want to make sure the rasters are being constructed row-wise or column-wise - use the byrow
arg to matrix
to adjust this, or transpose the matrix or otherwise arrange it.
您可能希望确保栅格是按行或逐列构建的 - 使用byrow arg to matrix来调整它,或者转置矩阵或以其他方式排列它。
#2
0
Your problem is that you're trying to convert nrows=3
into a raster
object, and then apply that new object as a function operating on each element of a.list
.
您的问题是您正在尝试将nrows = 3转换为栅格对象,然后将该新对象应用为对a.list的每个元素进行操作的函数。
You want either:
你想要:
lapply(a.list, raster, nrows=3, ncols=3)
Or:
要么:
lapply(a.list, function(X) raster(X, nrows=3, ncols=3))
#1
1
You probably need to convert your dataframes to matrices first. Exploit the fact that you have 1-column data frames to convert them to vectors and then use the matrix
function:
您可能需要先将数据帧转换为矩阵。利用以下事实:您有1列数据帧将它们转换为向量,然后使用矩阵函数:
> rl = lapply(a.list, function(X) raster(matrix(X[,1],nrow=3)))
> rl[[1]]
class : RasterLayer
dimensions : 3, 3, 9 (nrow, ncol, ncell)
resolution : 0.3333333, 0.3333333 (x, y)
extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : in memory
names : layer
values : 1, 9 (min, max)
You may want to make sure the rasters are being constructed row-wise or column-wise - use the byrow
arg to matrix
to adjust this, or transpose the matrix or otherwise arrange it.
您可能希望确保栅格是按行或逐列构建的 - 使用byrow arg to matrix来调整它,或者转置矩阵或以其他方式排列它。
#2
0
Your problem is that you're trying to convert nrows=3
into a raster
object, and then apply that new object as a function operating on each element of a.list
.
您的问题是您正在尝试将nrows = 3转换为栅格对象,然后将该新对象应用为对a.list的每个元素进行操作的函数。
You want either:
你想要:
lapply(a.list, raster, nrows=3, ncols=3)
Or:
要么:
lapply(a.list, function(X) raster(X, nrows=3, ncols=3))