I have a df with intervals of numbers, and I would like to split the numbers with a 'BETWEEN' and 'AND' between them (to use in a sqldf later)
t <- data.frame('id'=c(1:5), 'values'=c("1-1000", ">12", "2-2000", "<100", "5-10"), 'more values' =c(">50", "<10", "500-2000", "1-10", ">100") )
I am using a lapply function together with ifelse, it works, however, in the rest of the table all cells with a value that does not contain '-' are now replaced with a single number eg '1' or '2'. I would like the original values to be preserved (eg. >12. <100 etc..).
#with grepl
t[] <- lapply(t, function(x) ifelse(grepl('-', x), paste('BETWEEN', sub("\\-.*", "", x), 'AND', sub('.*-', '', x) ), x))
#with %like%
t[] <- lapply(t, function(x) if(x %like% '-') {paste('BETWEEN', sub("\\-.*", "", x), 'AND', sub('.*-', '', x))})
I have also tried with a if no else function, but it did not solve the problem
t[] <- lapply(t, function(x) if(grepl('-', x)) {paste('BETWEEN', sub("\\-.*", "", x), 'AND', sub('.*-', '', x))})
Desired ouput:
t1 <- data.frame('id'=c(1:5), 'values'=c("BETWEEN 1 AND 1000", ">12", "BETWEEN 2 AND 2000", "<100", "BETWEEN 5 AND 10"), 'more values' =c(">50", "<10", "BETWEEN 500 AND 2000", "BETWEEN 1 AND 10", ">100") )
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire