Nick Vence
Nick Vence

Reputation: 770

Error in is.data.frame(x) : object 'x' not found

I don't understand why I'm getting Error in is.data.frame(x) : object 'x' not found from the following code.

library(tidyverse)
data.frame(x = 1:3, y = 7:9) %>% 
  ggplot(aes(x,y)) +
  geom_point() +
  annotate("text", x = 1, y = 7,
           label = paste("sd(x) =", sd(x)))

Upvotes: 1

Views: 1896

Answers (1)

akrun
akrun

Reputation: 887691

We may need .data

 data.frame(x = 1:3, y = 7:9) %>% 
  ggplot(aes(x,y)) +
  geom_point() +
  annotate("text", x = 1, y = 7,
           label = paste("sd(x) =", sd(.data[["x"]])))

The issue with above method is that as we already give the location, the value extracted for 'x' column in that location is just a single value and thus sd on a single value returns NA. If we need the sd on the whole dataset, we may need a temporary object created

data.frame(x = 1:3, y = 7:9) -> tmp;
  ggplot(tmp, aes(x, y)) +
    geom_point() + 
    annotate("text", x = 1, y = 7, 
        label = paste('sd(x) = ', sd(tmp[['x']])))

Upvotes: 1

Related Questions