简体   繁体   English

如何一起使用 lapply 和 ifelse 但在 R 中的 df 中保留原始值

[英]How to use lapply and ifelse together but keep original values in the df in R

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)我有一个带有数字间隔的 df,我想在它们之间用“BETWEEN”和“AND”分​​割数字(稍后在 sqldf 中使用)

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'.我将 lapply 函数与 ifelse 一起使用,它可以工作,但是,在表的其余部分,所有值不包含“-”的单元格现在都替换为单个数字,例如“1”或“2”。 I would like the original values to be preserved (eg. >12. <100 etc..).我希望保留原始值(例如 >12。<100 等)。

#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我也试过 if no else 函数,但没有解决问题

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!提前致谢!

You can use ifelse with grepl and sub :您可以将ifelsegreplsub

t[-1] <- lapply(t[-1], function(x) 
         ifelse(grepl('-', x), paste0('BETWEEN ', sub('-', ' AND ', x)), x))
t
#  id             values          more.values
#1  1 BETWEEN 1 AND 1000                  >50
#2  2                >12                  <10
#3  3 BETWEEN 2 AND 2000 BETWEEN 500 AND 2000
#4  4               <100     BETWEEN 1 AND 10
#5  5   BETWEEN 5 AND 10                 >100

Using grepl we identify strings which have "-" in them and add "BETWEEN " and replace "-" with " AND " for them.使用grepl我们识别包含"-"字符串并添加"BETWEEN "并将"-"替换为" AND " We keep the other strings as it is.我们保持其他字符串不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM