Creating a column at a specific location in a dataframe

I want to create a new variable in a specific place. I can create a variable with mutateand then reorder with select, but I would rather do it tibble:add_column.

This is a simple example with aperture dataset:

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

I would really appreciate it if someone could tell me why my operator is ifelsenot working with add_column.

+4
source share
1 answer

The reason is that mutateor summariseetc. get the column value based on the character specification, but add_columnwill not be here . So we can extract the column using.$

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 i.e.

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

+6

Source: https://habr.com/ru/post/1692300/


All Articles