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
testand data values from the values ofyesorno.
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
srcrefattribute of functions is handled specially: iftestis a simple true result andyesevaluates to a function withsrcrefattribute,ifelsereturnsyesincluding its attribute (the same applies to a falsetestandnoargument). This functionality is only for backwards compatibility, the formif(test) yes else noshould be used wheneveryesandnoare 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.
