R Studio:为什么在相同的代码上按Ctrl + Enter可以正常工作时,为什么Alt + Enter有时会引发错误?

时间:2019-10-29 02:04:01

标签: r rstudio

library(tidyverse)
library(lubridate)
library(padr)

df <- tibble(`Action Item ID` = c("ABC", "EFG", "HIJ", "KLM", "NOP", "QRS"),
             `Date Created` = as.Date(c("2019-01-03", "2019-01-08", 
                                        "2019-06-09", "2019-06-11",
                                        "2019-08-12", "2019-08-21")),
             `Date Closed` = as.Date(c("2019-01-15", "2019-05-20", 
                                        "2019-06-15", NA,
                                        "2019-08-15", NA)),
             `Current Status` = c(rep("Closed", 5), "Open"))

df.long <- 
  df %>%
  select(-`Current Status`) %>% 
  pivot_longer(-c(`Action Item ID`),
               names_to = "Type",
               values_to = "Date") %>%
  mutate(Month = floor_date(Date, "month")) %>%
  replace_na(list(Month = max(floor_date(df$`Date Created`, "month")))) %>% 
  pad(by = "Month") %>% 
  fill(-Date, - Month)

df.long %>%  # line 25
  filter(!(Type == "Date Closed" & is.na(Date))) %>% 
  fill(Date) %>% 
  rbind(., df.long %>% filter(Type == "Date Closed" & is.na(Date))) %>% 
  arrange(`Action Item ID`, Date, desc(Type)) %>% 
  mutate(
    Age = as.integer(as.Date(ceiling_date(Month, unit = "month")) - Date)) %>% 
  mutate(Change = case_when(Type == "Date Created" & Age >= 90 ~ 1,
                            Type == "Date Created" & Age < 90 ~ 0))  # line 33

如果我将光标放在第25行的开头并按Alt+Enter,则代码块运行良好。但是,如果我将其放在第33行的末尾并按Alt+Enter,则会出现此错误:

Error: unexpected ')' in "    Age = as.integer(as.Date(ceiling_date(Month, unit = "month")) - Date))"
>   mutate(Change = case_when(Type == "Date Created" & Age >= 90 ~ 1,
+                             Type == "Date Created" & Age < 90 ~ 0))
Error in eval_tidy(pair$lhs, env = default_env) : object 'Type' not found

这是怎么回事,如何避免这种情况?另外,如果我突出显示整个代码块并点击Ctrl+Enter,那似乎还不错。虽然我会Ctrl+Enter间歇地运行一段代码,但会收到错误消息。我将立即重试,代码可以正常运行。这些仅仅是R代码库中的gremlins还是与R Studio相关?自几年前开始使用R和R Studio以来,我就注意到了这一点。

0 个答案:

没有答案