strengejacke / sjmisc

Data transformation and utility functions for R
https://strengejacke.github.io/sjmisc
GNU General Public License v3.0
158 stars 24 forks source link

sjmisc::rec() behaviour with mutate() and value ranges #131

Open konstruktur opened 4 years ago

konstruktur commented 4 years ago

Hi, I'd like to use sjmisc::rec() with value ranges within mutate(). I just found some of my written code that I think worked some months ago with sjmisc::rec(). But I'm now not completely sure whether this worked or not, at least I find the result, using rec() in mutate() with/without value ranges somehow inconsistent - but I think you can tell a little better whether this should work or not ;-) I prepared some examples. I use sjmisc v2.8.3 on R 3.6.1.

df.rec <- structure(list(x = c(2400, 1538.46153846154, 2500, 2638.88888888889, 
                     2083.33333333333, 5555.55555555556, 2666.66666666667, 2500, 2833.33333333333, 
                     2500, NA, 1750, 2833.33333333333, NA, 600, 1785.71428571429, 
                     2000, 2400, 1333.33333333333, 1333.33333333333)), row.names = c(NA, -20L), class = c("rowwise_df", "tbl_df", "tbl", "data.frame"))

### rec() without pipes # Works! Returns vector
sjmisc::rec(df.rec$x, rec="0:1258.99 = 1[below 1259]; 1259:max = 0[above 1259]; else=NA", var.label = "sjmisc::rec() test1")  

### rec() with pipes # Works! Returns df
df.rec %>% sjmisc::rec(x, rec="0:1258.99 = 1[below 1259]; 1259:max = 0[above 1259]; else=NA", var.label = "sjmisc::rec() test2")  

### rec() within mutate # Does not work: Error " 'to' must be a finite number"
df.rec %>% mutate(y = sjmisc::rec(x, rec="0:1258.99 = 1[below 1259]; 1259:max = 0[above 1259]; else=NA", var.label = "sjmisc::rec() test3"))  
#Error in seq.default(from, to) : 'to' must be a finite number
#In addition: Warning messages:
#1: In min(x, na.rm = T) : no non-missing arguments to min; returning Inf
#2: In max(x, na.rm = T) : no non-missing arguments to max; returning -Inf

### rec() within mutate, but without value ranges # Works with warnings
# Here I take out the spans and just recode a single value and copy the rest - and this works.
df.rec %>% mutate(y = sjmisc::rec(x, rec="2400 = 1[just 2400]; else=copy", var.label = "sjmisc::rec() test4"))  
#Warning messages:
# 1: In min(x, na.rm = T) : no non-missing arguments to min; returning Inf
#2: In max(x, na.rm = T) : no non-missing arguments to max; returning -Inf
#3: In min(x, na.rm = T) : no non-missing arguments to min; returning Inf
#4: In max(x, na.rm = T) : no non-missing arguments to max; returning -Inf

The latter works (with warnings). So I'm a bit confused whether my use with mutate() causes the above errors or the value ranges (e.g. 0:1258.99) I try to recode with.

Thanks fo any hint! Best, G