Search code examples
r-markdownrscript

R code works in script but not R markdown


#The code below works fine in my scripts but not in R markdown.

library(tidyverse)
library(scales)
age <- kaggle_2020_Survey %>%
  transmute(Q1 = as.factor(Q1)) %>% 
  filter(!is.na(Q1)) %>% 
  count(Q1) %>% 
  mutate(perc = n/sum(n)*100)


ggplot(age, aes(x = Q1, y = n)) + geom_col(fill = "darkblue", alpha =.7) +
geom_text (aes(x = Q1, y = n, label = paste0(round(perc,1), "%"),hjust = -.3), size = 3) 
+
coord_flip() + labs(title = "Age of participants", x = "Percent", y = "Number", 
subtitle = "Highest age group: 22-24") +
theme_classic() 

#This is the error I am getting: enter image description here


Solution

  • It could be that the object is in your environment but you forgot to include something like

    library(tidyverse)
    kaggle_2020_Survey <- read_csv("kaggle_2020_Survey.csv")
    
    

    where you load in the data. When you knit a rmarkdown file it starts a new session each time so if the data isn't called in before you start doing stuff then it will throw that error

    This answer goes into other solutions.