Car*_*rus 4 r tidyverse tibble
我想在特定位置创建一个新变量.我可以创建变量mutate然后重新排序,select但我宁愿选择tibble:add_column这样做的方式.
这是iris数据集的一个简单示例:
library(tidyverse)
## This works fine
iris %>% mutate(With_mutate = ifelse(Sepal.Length > 4 & Sepal.Width > 3 , TRUE, FALSE)) %>%
select(Sepal.Length:Petal.Width, With_mutate, everything()) %>%
head()
## This works also
iris %>% add_column(With_add_column = "Test", .before = "Species") %>%
head()
## This doesn't work
iris %>% add_column(With_add_column = ifelse(Sepal.Length > 4 & Sepal.Width > 3 , TRUE, FALSE), .before = "Species") %>%
head()
Error in ifelse(Sepal.Length > 2 & Sepal.Width > 1, TRUE, FALSE) :
object 'Sepal.Length' not found
Run Code Online (Sandbox Code Playgroud)
如果有人能告诉我为什么我的ifelse陈述无效,我将不胜感激add_column.
原因是mutate或者summarise等等根据指定符号得到列值,但是这里add_column不会.因此,我们可以提取列.$
iris %>%
add_column(With_add_column = ifelse(.$Sepal.Length > 4 &
.$Sepal.Width > 3 , TRUE, FALSE), .before = "Species") %>%
head()
#Sepal.Length Sepal.Width Petal.Length Petal.Width With_add_column Species
#1 5.1 3.5 1.4 0.2 TRUE setosa
#2 4.9 3.0 1.4 0.2 FALSE setosa
#3 4.7 3.2 1.3 0.2 TRUE setosa
#4 4.6 3.1 1.5 0.2 TRUE setosa
#5 5.0 3.6 1.4 0.2 TRUE setosa
#6 5.4 3.9 1.7 0.4 TRUE setosa
Run Code Online (Sandbox Code Playgroud)
只是为了使它紧凑,逻辑条件的值是TRUE/FALSE这样的,我们不需要一个ifelseie
add_column(With_add_column = .$Sepal.Length > 4 & .$Sepal.Width > 3, .before = "Species")
Run Code Online (Sandbox Code Playgroud)
可以取代第二步