[英]How to compute values within a defined region in a space in R?
I have data which looks like this:我有看起来像这样的数据:
identity growth x-pos y-pos
1: Z 0.1 0.5 0.7
2: B 0.1 0.1 0.0
3: C 0.2 4.6 2.5
4: D 0.3 5.6 5.0
5: A 0.4 0.2 1.0
6: P 0.1 0.4 2.0
Here, the each object with a unique identity is positioned on a 2d plane and the coordinates are denoted by x-pos y-pos (in micrometers) and has a certain growth value.在这里,每个具有唯一标识的对象位于一个二维平面上,坐标用x-pos y-pos (以微米为单位)表示,并具有一定的增长值。
What I want to do for every unique row or object having unique identity is this: 1.Compute the number of other objects with a unique identity within a circle of a specific radius (for eg. 2 micrometers) using the spatial coordinates.我想每一个唯一的行做或目标对象的唯一标识是这样的:1.Compute使用空间坐标与特定半径的圆内的唯一身份的其他对象(如2微米)的数量。 For instance, for object Z there are a certain number of other objects within a 2 micrometer radius.
例如,对于对象Z ,在 2 微米半径内有一定数量的其他对象。 2. Compute the mean of growth values for all objects within a certain radius from a focal object.
2. 计算距焦点对象一定半径内的所有对象的增长值的平均值。 Ideally, I want to do this for all unique objects and make a new data frame where
理想情况下,我想对所有独特的对象执行此操作并创建一个新的数据框
identity mean_ growth_2micrometers mean_growth_4micrometers mean_growth_6micrometers
1: Z 0.1 0.5 0.7
2: B 0.1 0.1 0.4
3: C 0.2 0.6 0.5
dist
can be used to get the distance between all points. dist
可用于获取所有点之间的距离。 Use this to identify which points are within the desired distance.使用它来确定哪些点在所需的距离内。
library(tidyverse)
df %>%
select(`x-pos`, `y-pos`) %>%
dist(diag = TRUE, upper = TRUE) %>%
as.matrix() %>%
as_tibble() %>%
set_names(df$identity) %>%
mutate(
identity = df$identity
) %>%
pivot_longer(cols = 1:6) %>%
inner_join(df %>% select(name=identity, growth)) %>%
group_by(identity) %>%
summarise(
mean_growth_2micrometers = mean(ifelse(value < 2, growth, NA), na.rm = TRUE),
mean_growth_4micrometers = mean(ifelse(value < 4, growth, NA), na.rm = TRUE),
mean_growth_6micrometers = mean(ifelse(value < 6, growth, NA), na.rm = TRUE)
)
#> # A tibble: 6 x 4
#> identity mean_growth_2micrometers mean_growth_4micrometers mean_growth_6micrometers
#> <chr> <dbl> <dbl> <dbl>
#> 1 A 0.175 0.175 0.18
#> 2 B 0.2 0.175 0.18
#> 3 C 0.2 0.25 0.2
#> 4 D 0.3 0.25 0.25
#> 5 P 0.2 0.175 0.18
#> 6 Z 0.175 0.175 0.18
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.