我需要过滤位于预定义区域内部或外部的坐标数据。我希望编写一个自定义函数来加快该过程。可以像这样在管道内插入的东西:
df %>%
filter(group == "A",
outside_area(x_coord,y_coord))
我不知道这在技术上是否合法,但想法是可以在dplyr管道中的某个地方调用它
这是使情况变得更加清楚的上下文。
# data
set.seed(123)
list <- c("A","B","C")
df <- tibble (group = sample(list, 500, replace=TRUE),
x = runif(500,0,105),
y = runif(500,0,68))
# plot all the data points
df %>% ggplot(aes(x=x,y=y)) +
geom_point()
# plot outside an area -- works
df %>%
filter(group == "A",
x <= 88.5 | (x >= 88.5 & y >= 43.2) | (x >= 88.5 & y <= 24.8)) %>%
ggplot(aes (x=x, y=y)) +
geom_point() +
xlim(0,105) +
ylim(0,69)
因此该功能将合并
x <= 88.5 | (x >= 88.5 & y >= 43.2) | (x >= 88.5 & y <= 24.8)
谢谢你的帮助
我们可以创建一个函数为
outside_area <- function(dat, col1, col2) {
dat[[col1]]<= 88.5 | (dat[[col1]] >= 88.5 & dat[[col2]] >= 43.2) | (dat[[col1]] >= 88.5 & dat[[col2]] <= 24.8)
}
df %>%
filter(group == "A", outside_area(., 'x', 'y'))
-输出
# A tibble: 164 x 3
# group x y
# <chr> <dbl> <dbl>
# 1 A 74.8 16.4
# 2 A 98.2 47.0
# 3 A 18.2 66.1
# 4 A 9.06 44.1
# 5 A 29.7 62.3
# 6 A 44.1 14.7
# 7 A 61.7 37.3
# 8 A 77.0 0.169
# 9 A 100. 54.4
#10 A 17.9 53.6
# … with 154 more rows
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句