除以r中的不等维矩阵 [英] Dividing matrices with unequal dimensions in r

查看:15
本文介绍了除以r中的不等维矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,我将其筛选到一个月中。我还有一个矩阵列表(l1),其长度与数据帧列表(int1)相同。列表中的矩阵具有不同的维度(例如,3x3、2x2)。

设置数据和列表:

library(lubridate)
library(tidyverse)
library(purrr)

date <- rep_len(seq(dmy("26-12-2010"), dmy("13-07-2011"), by = "days"), 200)
ID <- rep(c("A","B"), 100)
df <- data.frame(date = date,
                 x = runif(length(date), min = 60000, max = 80000),
                 y = runif(length(date), min = 800000, max = 900000),
                 ID)

df$jDate <- julian(as.Date(df$date), origin = as.Date('1970-01-01'))
df$Month <- month(df$date)

# First 10-day interval for `A`
t1 <- c(100,150,200)
# Second 10-day interval for `A`
t2 <- c(200,250,350)
# Third 10-day interval for `A`
t3 <- c(300,350, 400)
mat <- cbind(t1,t2, t3)

# First 10-day interval for `B`
t1 <- c(150,150)
# Second 10-day interval for `B`
t2 <- c(250,250)
mat2 <- cbind(t1,t2)

l1 <- list(mat, mat2)

int1 <- df %>%
  # arrange(ID) %>%   # skipped for readability of result
  mutate(new = floor_date(date, '10 day')) %>%
  mutate(new = if_else(day(new) == 31, new - days(10), new)) %>% 
  group_by(ID, new) %>%
  filter(Month == "3") %>% 
  group_split()
下面的代码尝试将lstMatl1分开。我遇到的问题是lstMat中的矩阵与l1中的矩阵的维度不同。由于这种差异,当我尝试将一个与另一个分开时,收到错误消息:Error in .x/.y : non-conformable arrays

g1 <- as.integer(gl(length(int1), 3, length(int1)))

f2 <- function(.int1, .int2) {
  t(outer(seq_along(.int1), seq_along(.int2), 
          FUN = Vectorize(function(i, j)  min(.int1[[i]]$jDate) - 
                            min(.int2[[j]]$jDate))))
}
lstMat <- map2(split(int1, g1), split(int1, g1), f2)
map2(l1, lstMat[1:2], `/`)

关于如何修改此代码以允许列表中的矩阵存在差异,您有什么想法吗?

问题: 我有不同维度的矩阵,我一直在尝试除法。假设我运行一个定制函数,并以l1结束。l1中的矩阵对应于int1中的10天间隔,但我们没有得到IDB的第三个10天间隔的输出,因此是2x2矩阵。

规则: 在本例中,我想删除lstMat[[2]]中的第三列,因为这是l1[[2]]中缺少的一列。情况并不总是如此,例如,如果l1[[2]]中缺少第二个10天间隔,则我希望删除lsMat[[2]]中的第二列。

我想根据最终从lstMat中删除的特定间隔,通过使用int1来链接lstMatl1

我希望我没有把这件事弄得更混乱。如果我做了,我道歉。

感谢您抽出时间。

推荐答案

此处,‘g1’需要基于‘lstMat’中每个元素的行数/维度是动态的。这可以通过rep

来完成
library(purrr)
g1 <- rep(seq_along(lstMat), sapply(lstMat, nrow))
lstMat <- map2(split(int1, g1), split(int1, g1), f2)
map2(l1, lstMat[1:2], `/`)
[[1]]
      t1  t2  t3
[1,] Inf  20  15
[2,] -15 Inf  35
[3,] -10 -35 Inf

[[2]]
      t1  t2
[1,] Inf  25
[2,] -15 Inf

有些值Inf只是因为我们在‘lstMat’中有一些值作为‘0’

lstMat[1:2]
$`1`
     [,1] [,2] [,3]
[1,]    0   10   20
[2,]  -10    0   10
[3,]  -20  -10    0

$`2`
     [,1] [,2]
[1,]    0   10
[2,]  -10    0

因此,任何值除以0都会返回Inf

这篇关于除以r中的不等维矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆