Andrew C
Andrew C

Reputation: 79

R using pipe instead of $ syntax

Syntax question. I want to filter a data set then run cor.test() without altering the original data set. I can do this in separate lines and by creating a separate data frame.

library(dplyr)

df <- data(trees)
df <- filter(trees, Girth >12)
cor.test(df$Girth, df$Height)

However I'm trying to be more efficient. I want to do the same thing in a pipe and without needing to creating a new data frame. Specifically, what is the syntax for eliminating the $ for selecting columns?

Upvotes: 1

Views: 83

Answers (1)

s_baldur
s_baldur

Reputation: 33488

You can use with():

library(dplyr)

filter(trees, Girth > 12) |> 
  with(cor.test(Girth, Height))

In base R:

subset(trees, Girth > 12) |> 
  with(cor.test(Girth, Height))

Upvotes: 3

Related Questions