R - Selecting elements of a data frame with a column that has the same name as a global variable with`dplyr`

Asked

Viewed 552 times

5

Consider the following data.frame and the variable x

df <- data.frame(x = c(rep(0, 10), rep(1, 10)), y = 1:20)
x <- 0

I tried to use the dplyr to select column elements x equal to the global variable x

library(dplyr)
df %>% filter(x == x))

But I got all the data.frame in the answer. The filter should be considering only the column, I imagine.

As I point out to the filter that one of x is a global variable?

2 answers

5


Utilize .GlobalEnv$x:

library(dplyr)
df %>% 
  filter(x == .GlobalEnv$x)

   x  y
1  0  1
2  0  2
3  0  3
4  0  4
5  0  5
6  0  6
7  0  7
8  0  8
9  0  9
10 0 10

2

With the aid of dplyr it is also possible to use the operator !! or the function UQ.

library(dplyr)
df %>% filter(x == UQ(x))

Or

df %>% filter(x == !!(x))

This operation "indicates to R" that the first step to be performed in the code is the evaluation of the x.

Source: R Documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.