简体   繁体   English

R 等效于 SQL 中的情况?

[英]R equivalent of case when in SQL?

I have been using T-SQL for a while but I now have to make transition to R...我使用 T-SQL 已经有一段时间了,但我现在必须过渡到 R...

select case when date_column_1 < '20160801' then date_column_1 else '20160801' end as date_column_1, case when date_column_2 < '99991231' then '20190701' else date_column_2 end as date_column_2 from table

Also, apologies in advance with my crappy stackoverflow formatting skills.另外,请用我糟糕的stackoverflow格式化技巧提前道歉。

Since you have only one condition to check for each column, we can use ifelse here.由于您只有一个条件来检查每一列,因此我们可以在此处使用ifelse If there are multiple conditions you could check case_when from dplyr .如果有多个条件,您可以从dplyr case_when

transform(table, date_column_1 = ifelse(date_column_1 < as.Date('2016-08-01'), 
                                        date_column_1, as.Date('2016-08-01')), 
                 date_column_2 = ifelse(date_column_2 < as.Date('9999-12-31'),
                                        as.Date('2019-07-01'), date_column_2))

Assuming date_column_1 and date_column_2 are of Date class, you cannot directly compare dates with literal string ( "20160801" ) in R, so we convert the dates to compare to Date class as well.假设date_column_1date_column_2是日期 class,您不能直接将日期与 R 中的文字字符串( "20160801" )进行比较,因此我们将日期转换为日期 ZABCBA2F2ED4F8EB402 作为比较。 Moreover, for date_column_2 do you mean to replace all values with the date "2019-07-01" ?此外,对于date_column_2 ,您的意思是用日期"2019-07-01"替换所有值吗?


As mentioned by @G.正如@G所提到的。 Grothendieck ifelse would convert the dates to numeric. Grothendieck ifelse会将日期转换为数字。 We can use if_else from dplyr which is type-strict and will maintain the dates.我们可以使用if_else中的dplyr ,它是类型严格的,并且会保留日期。

library(dplyr)

table %>%
   mutate(date_column_1 = if_else(date_column_1 < as.Date('2016-08-01'), 
                            date_column_1, as.Date('2016-08-01')), 
          date_column_2 = if_else(date_column_2 < as.Date('9999-12-31'),
                            as.Date('2019-07-01'), date_column_2)))

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

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