![](/img/trans.png)
[英]Is there a more efficient way to assign categories in R than using a loop?
[英]Is there a more efficient way to fill extra column than a 'for' loop?
我有一个大约有10万行的data.table。 我将简化为3列,因为这就是所有相关的。
dt <- data.table(indicator = c("x", "y"),
date1 = c("20190111", "20190212", "20190512", "20190723"),
date2 = c("20190105", "20190215", "20190616", "20190623"))
我想要做的是将date1或date2分配给新列,'final_date'取决于指标列。 如果指标为“x”,则将final_date指定为date1。 如果指标“y”将final_date指定为date2。
我可以使用“for”循环和if / else语句来完成此操作,但需要几分钟才能完成100k行。
for (row in 1:nrow(dt)) {
if(dt$indicator[row] == "x") {
dt$final_date[row] <- dt$date1[row]
} else {
dt$final_date[row] <- dt$date2[row]
}
}
有没有更有效的方法来执行data.table功能或其他任何事情?
有了data.table
,我会做这样的事情:
dt[, final_date := ifelse(indicator == "x", date1, date2)]
真快捷简单! 我怀疑使用大量数据时它会比dplyr
以及你所拥有的解决方案更快,因为data.table
在适当位置发生变异,而不是创建数据副本。
使用dplyr
管道
> dt%>%mutate(final_data=if_else(indicator=="x",date1,date2))
indicator date1 date2 final_data
1 x 20190111 20190105 20190111
2 y 20190212 20190215 20190215
3 x 20190512 20190616 20190512
4 y 20190723 20190623 20190623
尝试这个:
# necessary package
library(dplyr)
library(data.table)
# reproduce your data
dt <- data.table(
indicator = c("x", "y"),
date1 = c("20190111", "20190212", "20190512", "20190723"),
date2 = c("20190105", "20190215", "20190616", "20190623")
)
# create your variable final_date
dt[, final_date := case_when(indicator == "x" ~ date1,
TRUE ~ date2)]
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.