I spent 45 mins to get a very simple if()
inside a loop to work, but I want to understand why it was failing in the first place.
It's a simple R Magrittr pipe chain with a if()
condition in braces {}
Here's the simplified reprex (reproducible example)
library(tidyverse) # load tidyverse library
# function to check the data type of a column
# Fails
check1 <- function(.df, .colm)
{
.df %>%
{ if(. %>% pull(var = ) %>% is.character()) 1 else 2} # pull .colm from .df and check if is char
}
# Works
check2 <- function(.df, .colm)
{
.df %>%
{if(pull(., var = ) %>% is.character()) 1 else 2} # pull .colm from .df and check if is char
}
check1(a, a1) # Fails
#> Error in eval(lhs, parent, parent): object 'a' not found
check2(a, a1) # Works
#> Error in eval(lhs, parent, parent): object 'a' not found
Created on 2021-03-29 by the reprex package (v0.3.0)
Also do let me know if there's a simpler way to do what I'm trying to do
Aucun commentaire:
Enregistrer un commentaire