简体   繁体   中英

“could not find function %>%<-”, issue with tidyr package and the %>% operator

I'm working on a script for a swirl lesson on using the tidyr package and I'm having some trouble with the %>% operator. I've got a data frame called passed that contains the name, class number, and final grade of 4 students. I want to add a new column called status and populate it with a character vector that says "passed". Before that, I used select to grab some columns from a data frame called students4 and stored it in a data frame called grade book

gradebook <- students4 %>%
select(id, class, midterm, final) %>%
passed<-passed %>% mutate(status="passed")

Swirl problems build on each other, and the last one just had me running the first to lines of code, so I think those two are correct. The third line was what was suggested after a couple of wrong attempts, so I think there's something about %>% that I'm not understanding. When I run the code I get an error that says;

Error in students4 %>% select(id, class, midterm, final) %>% passed <- passed %>%  : 
  could not find function "%>%<-

I found another user who asked about the "could not find function "%>%" who was able to resolve the issue by installing the magrittr package, but that didn't do the trick for me. Any input on the issues in my code would be super appreciated!

It's not a problem with the package or the operator. You're trying to pipe into a new line with a new variable.

The %>% passes the previous dataframe into the next function as that functions df argument.

Instead of doing all of this:

Gradebook <- select(students4, id, class, midterm, final)
Gradebook2 <- mutate(Gradebook, test4 = 100) 
Gradebook3 <- arrange(Gradebook2, desc(final))

You can pipe operator into the next argument if you're working on the same dataframe.

Gradebook <- students4 %>% 
      select(students4, id, class, midterm, final) %>%
      mutate(test4 = 100) %>%
      arrange(desc(final))

Much cleaner and easier to read.

In your second line you're trying to pass it to a new function but instead of there being a function you're all of a sudden defining a variable. I don't know the exercise you're doing but you should remove the second operator.

gradebook <- students4 %>%
select(id, class, midterm, final)

passed <- passed %>% mutate(status="passed")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM