gpt4 book ai didi

r - 通过两个数据帧和一个矩阵进行匹配和索引

转载 作者:行者123 更新时间:2023-12-02 01:39:11 25 4
gpt4 key购买 nike

  1. 我有一个数据框 events具有独特点的 xy 坐标。
  2. 我有一个数据框 all_nodes带有网络节点的 xy 坐标。 events的所有积分也在 all_nodes ,但不一定只一次,并且在不同的位置,即 events 中的点的索引(行 ID)不对应于all_nodes .
  3. 我有一个矩阵 ma尺寸nrow(all_nodes)nrow(all_nodes)计算出所有节点之间的成对交互项。 ma rows 和 cols 对应于 all_nodes 的索引 (row_ids) .

我的总体目标是识别 events 的行 ID在all_nodes 。借此,我的目标是从我的矩阵 ma 中提取成对相互作用的子矩阵根据检测到的行 ID。最后我想更改 submtarix 的顺序,使 ids 和对应点对应于 events 。非常感谢任何类型的帮助(代码/引用/提示)!

玩具数据(您可以在下面找到真实数据)

# coords of unique events 
events <- data.frame(x = c(1,2,3,4),
y = c(4,3,2,1))
# all_nodes
all_nodes <- data.frame(x = c(2,1,120,3,150,4,1),
y = c(3,4,120,2,150,1,4))
# matrix corresponding to the index of all_nodes
ma <- matrix(data = rnorm(n = 49, mean = 3, sd = 1),
nrow = nrow(all_nodes), ncol = nrow(all_nodes))
ma[6, ] <- ma[2, ]

我的努力并没有多大帮助,因为我遇到了几个问题。

# coords of unique events 
events # see toy data

# ------------------------------------------------
# from object g of class "sfnetwork" "tbl_graph" "igraph"
# all rounded coords of nodes; from g ma is used
# in several steps
# cols and rows in ma correspond to node ids of g/all_nodes

# all_nodes <- g %>% tidygraph::activate("nodes") %>%
# as.data.frame(geometry)
# all_nodes <- as.data.frame(matrix(unlist(all_nodes$geometry), ncol = 2, byrow = TRUE))
# names(all_nodes) <- c('x', 'y')
# all_nodes <- round(all_nodes, 2)
# --------------------------------------------------

# matching based on x-coord only
ix <- which(all_nodes$x %in% events$x)
# Problem A
length(ix) == nrow(events) # different length
# Problem B
# and the event with coords x=1, y=4 occurs twice in ix

sub <- ma[ix, ix]
# If problems A+B were eleminated, sub would correspond to
# all events, but I different indexing makes it unusable #(several permutations possible)

我也玩过 st_equals {sf}直接使用 events <- sf::st_as_sf(events[, c('x', 'y')], coords = c('x', 'y')) 比较几何形状在上一步中。

真实数据

# removed 

最佳答案

交互可用于在多个列上匹配

idx <- match(interaction(events), interaction(all_nodes))
ma[idx,idx]

关于r - 通过两个数据帧和一个矩阵进行匹配和索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71894307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com