Home > Net >  ifelse() returns NA for certain true/false class values
ifelse() returns NA for certain true/false class values

Time:01-13

Is there some restrictions of the types of values ifelse() can return?

For:

v = c(1,2)
l1 = list(11)
l2 = list(22)
> ifelse(v==1, l1, l2)
[[1]]
[1] 11

[[2]]
[1] 22

as expected, but:

hp0 = fp_text_lite() 
hp = fp_text_lite(bold = TRUE, shading.color = "yellow" ) 
ifelse(v==1, hp, hp0)

[[1]]
[1] NA

[[2]]
[1] NA

CodePudding user response:

Looking at the ?ifelse help page, the value returned by ifelse is

A vector of the same length and attributes (including dimensions and "class") as test and data values from the values of yes or no.

If you have a mismatch between dimensions, lengths, and attributes of the arguments you should not expect it to work.

If you put your result options in a list(), they can be recycled properly to the length of your vector and this will actually work:

ifelse(v==1, list(hp), list(hp0))
# [[1]]
#   size italic bold underlined color shading fontname fontname_cs fontname_eastasia
# 1   NA     NA TRUE         NA    NA  yellow       NA          NA                NA
#   fontname.hansi vertical_align
# 1             NA       baseline
# 
# [[2]]
#   size italic bold underlined color shading fontname fontname_cs fontname_eastasia
# 1   NA     NA   NA         NA    NA      NA       NA          NA                NA
#   fontname.hansi vertical_align
# 1             NA       baseline

Is there some restrictions of the types of values ifelse() can return?

Yes, ifelse has trouble with functions. Again, rom the ?ifelse help page (emphasis mine):

The srcref attribute of functions is handled specially: if test is a simple true result and yes evaluates to a function with srcref attribute, ifelse returns yes including its attribute (the same applies to a false test and no argument). This functionality is only for backwards compatibility, the form if(test) yes else no should be used whenever yes and no are functions.

Generally, ifelse is good for vectors. For a length-one condition if(){}else{} is better. For things that don't go well in vectors, like functions, apply family functions or purrr functions are probably better.

  •  Tags:  
  • Related