Home > Net >  How to pass the filtered dataframe to a subsequent function?
How to pass the filtered dataframe to a subsequent function?

Time:06-14

I'm trying to pass a filtered dataframe onto a subsequent function. Consider Iris dataframe. I filter out only on Versicolor species and then I want to use Sepal.Length and Sepal.Width column into a function that takes two vectors. I'm currently trying to implement DouglasPeuckerNbPoints, so I will use this as an example

iris %>% 
  filter(
    (Species == "versicolor"))

I have tried:

library(kmlShape)
iris %>% 
  filter(
    (Species == "versicolor")) %>%
      DouglasPeuckerNbPoints(.$Sepal.Length,.$Sepal.Width,20)

But this is giving me the error "Error in xy.coords(x, y, setLab = FALSE) : 'x' and 'y' lengths differ".

Any help here?

CodePudding user response:

The following works. We can put the function inside {}. This is called lambda expression as there are more than one dot. See https://magrittr.tidyverse.org/reference/pipe.html for more information.

library(tidyverse)
library(kmlShape)

iris %>% 
  filter(Species == "versicolor") %>%
  {DouglasPeuckerNbPoints(trajx = .$Sepal.Length, 
                         trajy = .$Sepal.Width, 20)}
#      x   y
# 1  7.0 3.2
# 2  4.9 2.4
# 3  6.6 2.9
# 4  5.2 2.7
# 5  5.0 2.0
# 6  5.9 3.0
# 7  6.0 2.2
# 8  5.6 2.9
# 9  6.7 3.1
# 10 5.6 3.0
# 11 6.2 2.2
# 12 5.9 3.2
# 13 6.7 3.0
# 14 5.5 2.4
# 15 5.4 3.0
# 16 6.7 3.1
# 17 6.3 2.3
# 18 5.6 3.0
# 19 5.0 2.3
# 20 5.7 2.8
  • Related