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

标签 r dataframe matrix indexing matching

  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/

相关文章:

r - 计算 R 数据帧中的增长百分比

python - 忽略索引的两个数据帧的快速减法(Python)

python - R/rpy2 中 as.dist 函数的内存问题

r - 如何将数据帧 A 中的每一列重复除以数据帧 B 中同一列的中位数?

r - 使用 svm 时绘图错误、公式丢失

reshape 矩阵以获得网络

python - 从数据框或系列的 Pandas 输出中删除名称、数据类型

matlab - 如何将元胞数组分配给多个矩阵?

c++ - 类内类问题

c++ - 投影和 View 矩阵