![](/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.