我有一个数据集,我已经过滤成一个月了。我还有一个矩阵列表(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()下面的代码试图将lstMat与l1分开。我遇到的问题是,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天间隔,但是我们没有得到ID B的第三个10天间隔的输出,因此得到了2x2矩阵。
规则:在本例中,我希望从lstMat[[2]]中删除第三列,因为这是l1[[2]]中缺少的一列。情况并不总是如此,例如,如果l1[[2]]中缺少第二个10天间隔,那么我希望删除lsMat[[2]]中的第二列。
我想通过使用lstMat和l1来链接int1,这是基于最终从lstMat中删除的特定间隔。
我希望我没有让这件事更令人困惑。如果我这么做了我很抱歉。
谢谢您抽时间见我。
发布于 2022-01-12 20:24:15
在这里,'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
https://stackoverflow.com/questions/70673876
复制相似问题