【问题标题】:Fixing mismatched matrices修复不匹配的矩阵
【发布时间】:2021-12-29 14:04:00
【问题描述】:

我有一个数据集df,它被分成int1和int2. In int1andint2, there is two elements for the IDA and three elements for theID`B。

我的目标是为ID A 创建一个 2x2 矩阵,为ID B 创建一个 3x3 矩阵,并将其从我的矩阵示例列表l1 中划分出来。目前,我的代码正在为ID A 创建一个3x3 矩阵,为ID B 创建一个2x2 矩阵,使用g1f2 的产品组合使用map2() 得到lstmat

关于如何获得ID A 的 2x2 矩阵和ID B 的 3x3 矩阵的所需输出的任何建议?

示例数据:

library(lubridate)
library(tidyverse)
date <- rep_len(seq(dmy("26-12-2010"), dmy("20-12-2011"), by = "days"), 500)
ID <- rep(c("A","B"), 5000)
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)
df$year <- year(df$date)

t1 <- c(100,150)
t2 <- c(200,250)
mat <- cbind(t1,t2)

t1 <- c(150,150,200)
t2 <- c(250,250,350)
t3 <- c(350,350, 400)
mat2 <- cbind(t1,t2, t3)

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()

int2 <- 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 == "2") %>% 
  group_split()

names(int1) <- sapply(int1, function(x) paste(x$ID[1], 
                                             sep = '_'))
names(int2) <- sapply(int2, function(x) paste(x$ID[1], 
                                              sep = '_'))
int1 <- int1[-1]
int2 <- int2[-1]

对于更改此代码以获得所需结果的任何建议? :

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(int2, g1), f2)
map2(l1, lstMat, `/`)

【问题讨论】:

    标签: r list matrix dplyr tidyverse


    【解决方案1】:

    由于'int1'、'int2'在names上重复了namessplit,而不是用gl创建分组索引

    lstMat <- map2(split(int1, names(int1)), split(int2, names(int2)), f2)
    map2(l1, lstMat, `/`)
    

    -输出

    [[1]]
               t1       t2
    [1,] 3.571429 5.263158
    [2,] 8.333333 8.928571
    
    [[2]]
                t1        t2        t3
    [1,]  5.357143  6.578947  7.291667
    [2,]  8.333333  8.928571  9.210526
    [3,] 25.000000 19.444444 14.285714
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      相关资源
      最近更新 更多