rdplyriris-dataset

Using the pipe function in R by assigning values, Is my approach correct?


enter image description here

This is my first time using the pipe function and my professor has not reviewed how to use it so

I am a little lost, I have trouble with the last question since I keep getting error most likely since the last

assignment contradicts my filter <=2, Thank you in advance, The following is my code:

L.W<- iris %>%
select(Petal.Length,Petal.Width) %>% head()
print(L.W)  

#b
S.L <- iris%>%
arrange(Sepal.Length)%>%
head()
print(S.L)  

#c
iris%>
arrange(Sepal.Length)%>%
select(Species,Petal.Length,Petal.Width)%>%
head()

#Switch order 
iris%>%
select(Species,Petal.Length,Petal.Width)%>%
head()

#there are two different data sets 

#d
iris%>%
filter(Petal.Length<=2 & Petal.Width< mean(Petal.Width))%>%
mutate(Petal.Length)%>%
huge<-assign(Petal.Length>6)%>%
big<-assign(Petal.Length>5)%>%
medium<-assign(Petal.Length>4)%>%
small<-assign(Petal.Length<=4)%>%
head()

Solution

  • Explanation: The solution for task #d: Using filter select observations where Petal.Length is not <=2 !Petal.Length <= 2 and ... Then we use mutate with case_when

    #d
    iris %>% 
      filter(!Petal.Length <= 2 & !Petal.Width < mean(Petal.Width)) %>% 
      mutate(new_col = case_when(Petal.Length > 6 ~ "huge",
                                 Petal.Length > 5 ~ "big",
                                 Petal.Length > 4 ~ "medium",
                                 Petal.Length <= 4 ~ "small")) %>% 
      head()
      
    

    Output:

      Sepal.Length Sepal.Width Petal.Length Petal.Width    Species new_col
    1          7.0         3.2          4.7         1.4 versicolor  medium
    2          6.4         3.2          4.5         1.5 versicolor  medium
    3          6.9         3.1          4.9         1.5 versicolor  medium
    4          5.5         2.3          4.0         1.3 versicolor   small
    5          6.5         2.8          4.6         1.5 versicolor  medium
    6          5.7         2.8          4.5         1.3 versicolor  medium