在数据框中的特定位置创建一列

Create a column at specific location in dataframe

我想在特定位置创建一个新变量。我可以使用 mutate 创建变量,然后使用 select 重新排序,但我更喜欢 tibble:add_column 的方式。

这是鸢尾花数据集的一个简单示例:

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

如果有人能告诉我为什么我的 ifelse 语句不适用于 add_column,我将不胜感激。

原因是mutatesummarise等是根据指定符号获取列值,而这里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

只是为了使其紧凑,逻辑条件的值为 TRUE/FALSE 所以,我们不需要 ifelse

add_column(With_add_column = .$Sepal.Length > 4 & .$Sepal.Width > 3, .before = "Species")

可以代替第二步