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

4

我希望在特定位置创建一个新的变量。我可以使用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时无法正常工作。
1个回答

6
原因在于 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")

可以替换第二步


1
非常感谢 @akrun 提供这么快的答案。另外,建议去掉没有意义的 ifelse - Carpatorus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接