代码之家  ›  专栏  ›  技术社区  ›  Omry Atia

对于每个数据帧行,查找位于特定范围内的点

  •  2
  • Omry Atia  · 技术社区  · 7 年前

    我有一个数据框 m 行列 n

    我希望每一点都定义一个 N -尺寸立方体(最好点位于该立方体的中心,取决于每个轴中的值是否为中心),每边等于0.2,并计算该立方体中有多少数据点。

    例如:

    df <- structure(list(x1 = c(0, 0.01, 0.05, 0.07, 0.1, 0.11, 0.16, 0.18, 
    0.2, 0.25, 0.5), x2 = c(0.05, 0.3, 0.1, 0.17, 0.38, 0.01, 0.04, 
    0.05, 0.11, 0.21, 0.26), x3 = c(0.4, 0.07, 0.09, 0.1, 0.23, 0.4, 
    0.2, 0.11, 0.01, 0.34, 0.22)), row.names = c(NA, -11L), class = c("tbl_df", 
    "tbl", "data.frame"))
    

    第一个点不能是立方体的中心,因为它是 x y

    x1 >= 0 and x1 <= 0.2
    x2 >= 0 and x2 <= 0.2
    x3 >= 0.3 and x3 <= 0.5
    

    因此,第一个立方体仅包含点(0,0.05,0.4)和(0.11,0.01,0.4)。

    第二个点定义立方体:

    x1 >= 0 and x1 <= 0.2
    x2 >= 0.2 and x2 <= 0.4
    x3 >= 0 and x3 <= 0.2
    

    并且只包含它自己。

    M (基础或 dplyr

    有什么想法吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   mickey    7 年前

    这将查看点与其立方体中心之间的距离。最大距离(在任何尺寸中)小于或等于 0.1 就在那个立方体里面。

    lower_edge = 0.5*((df - 0.1) + abs(df - 0.1))
    lower_edge = 0.5*((lower_edge + 0.8) - abs(lower_edge - 0.8))
    upper_edge = lower_edge + 0.2
    cube_center = 0.5*(lower_edge + upper_edge)
    m = NROW(df)
    n = NCOL(df)
    dists = as.matrix(dist(rbind(df, cube_center), method = "maximum"))[(m+1):(2*m), 1:m]
    apply(dists, 1, function(x) sum(x <= 0.1))
    

    (我假设您不希望任何多维数据集的点超出[0,1]^n)