r - 在 R 中使用循环从列表中填充数组
问题描述
我在 R 中有一个列表,其中包含逐月逐层的叶面积值,就像这样
ls <- list(month = c(1,1,2,2,3,3,4,4),
layer = c(0,1,0,1,0,1,0,1),
LA = c(runif(8)))
我想创建一个数组,每个月按层显示 LA 的快照,第 0 层对应于数组中每个矩阵的底部,第 1 层对应于顶部。我创建了一个数组
canopy <- array(dim = c(2,1,4))
并试图用 for 循环填充它
for (i in 1:4) {
if (ls$month == i){
if (ls$layer == 0){
canopy[2,1,i] <- ls$LA
} else if (ls$layer == 1){
canopy[1,1,i] <- ls$LA
}}}
但是,这会产生错误
Error in canopy[2, 1, i] <- ls$LA :
number of items to replace is not a multiple of replacement length
In addition: Warning messages:
1: In if (ls$month == i) { :
the condition has length > 1 and only the first element will be used
2: In if (ls$layer == 0) { :
the condition has length > 1 and only the first element will be used
我怎样才能清理这个?
解决方案
将数据放入 3 维矩阵总是很棘手。确保这确实是您所需要的。对于此示例,标准矩阵/数据框可能是更好的解决方案。
在这个解决方案中,我遍历月数并确定每个月的向量索引,然后从列表的每个向量中提取这些元素。棘手的部分之一是图层为 0 或 1。R 中没有 0 索引(Python 是的),因此我在图层中添加了一个以将其正确放置在矩阵中。
试试这个:
ls <- list(month = c(1,1,2,2,3,3,4,4),
layer = c(0,1,0,1,0,1,0,1),
LA = c(runif(8)))
canopy <- array(dim = c(2,1,4))
#Rows are layer
#Columns are LA
#Matrixes are month
for (i in 1:4) {
month <- which(ls$month ==i)
canopy[ls$layer[month]+1, ,i] <-ls$LA[month]
}
canopy
, , 1
[,1]
[1,] 0.1941003
[2,] 0.5879553
, , 2
[,1]
[1,] 0.8284857
[2,] 0.7242819
, , 3
[,1]
[1,] 0.8078793
[2,] 0.3489988
, , 4
[,1]
[1,] 0.25424950
[2,] 0.05117571
推荐阅读
- java - 使用 java 从图像文件中裁剪酒店对象
- python - 使用 pyaudio 从音频输入中获取特定频率
- python - 如何仅使用重复键合并字典中的选择值
- laravel-5 - Laravel 记录“在命令行代码中找不到类 'Arr':1”
- windows - 为什么 Android Studio 拒绝在 GitHub 上共享项目?
- javascript - 如何从Javascript为元素中的输入值设置值?
- bash - 使用 bash 的 ssh-remote 插件的代码命令
- python - 使用 POST 请求提交表单后出现错误 404
- c# - 安全问题 AspNetCore Identity
- c# - C# winforms 图形超大