jeudi 25 avril 2019

Why does base R `ifelse()` turn my character vectors into matrices intermittently?

library(tidyverse)
df <- tibble(col1 = c(5, 2), col2 = c(6, 4), col3 = c(9, 9))
# # A tibble: 2 x 3
#    col1  col2  col3
#   <dbl> <dbl> <dbl>
# 1     5     6     9
# 2     2     4     9


df.cha <- df %>% mutate(col4 = ifelse(apply(.[, 1:3], 1, sd) > 3,
                                      "True",
                                      "False"))
df.cha$col4
#[1] "False" "True" 

The code above works fine. Column 4 is a column of characters as I'd expect. However, I can add one extra condition to my ifelse statement, that being & .[, 3] > 0, and all of a sudden R is creating matrices for column 4 instead of leaving it as a character vector like I want. See below.

Why is this?

df.mat <- df %>% mutate(col4 = ifelse(apply(.[, 1:3], 1, sd) > 3 & 
                                        .[, 3] > 0,  # I only added this
                                      "True",
                                      "False"))
df.mat$col4
#      col3   
# [1,] "False"
# [2,] "True" 

Aucun commentaire:

Enregistrer un commentaire