通过分配值在 R 中使用管道函数,我的方法正确吗?

问题描述

enter image description here

这是我第一次使用管道函数,我的教授还没有复习如何使用它

我有点失落, 我在最后一个问题上遇到了麻烦,因为自上次以来我很可能一直收到错误

赋值与我的过滤器相矛盾

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.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()

解决方法

说明: 任务#d 的解决方案: 使用 filter 选择观察,其中 Petal.Length 不是 !Petal.Length <= 2 并且 ... 然后我们使用 mutatecase_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()
  

输出:

  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