在一个变量中对多个观察进行分类,以便我可以在新列中对它们进行分类. 如何使代码更短? 在 R 中



我正在寻找一种捷径或劳动强度较低的方法,将某些观察结果分组在同一变量中,然后输出到依赖于的新列中。

axa$type[axa$instrument_type == "CORPORATE BONDS" | axa$instrument_type == "GOVERNMENT BONDS"] <- 'BONDS'
axa$type[axa$instrument_type == "FOREIGN CURRENCY"] <- 'Cash'
axa$type[axa$instrument_type == "FUT-FIXED INCOME"] <- 'Derivatives'
axa$type[axa$instrument_type  ==  "INTEREST RATE SWAP"] <- 'Derivatives'
axa$type[axa$instrument_type == "MUTUAL FUNDS"] <- 'Funds'
axa$type[axa$instrument_type == "SHORT TERMS"] <- 'Cash Equivalent'
axa$type[axa$instrument_type == "CMO"] <- 'Other Fi'
axa$type[axa$instrument_type == "NON-SECY ASSET STOCK"] <- 'Other'

代码搜索某些观察结果,然后将在 axa$type 列中输出,所需的输出:"现金"、"衍生品"。

有没有办法使这段代码更短/紧凑。 最好使用数据表包

更简单的选择是创建键/值数据集对,然后执行联接。 这是可扩展的,它只需要一个联接,而不是多次执行==和分配

library(data.table)
keydat <- data.table(instrument_type = c("CORPORATE_BONDS", "FOREIGN_CURRENCY",
...), type = c("GOVERNMENT", "Cash",...))
setDT(axa)[keydat, type := i.type, on = .(instrument_type)]

注意:...是"instrument_type"中的剩余值和相应的"类型"值

不是很短,但使用dplyr中的case_when会使其更干净,避免每次都写入dataframe_name$column_name。您可以使用%in%而不是|来比较instrument_type中的多个值。

library(dplyr)
axa %>%
mutate(type = case_when(
instrument_type %in% c("CORPORATE BONDS","GOVERNMENT BONDS") ~ "BONDS", 
instrument_type == "FOREIGN CURRENCY" ~ "Cash", 
instrument_type %in% c("FUT-FIXED INCOME", "INTEREST RATE SWAP") ~ "Derivatives", 
instrument_type == "MUTUAL FUNDS"~"Funds", 
instrument_type == "SHORT TERMS" ~ "Cash Equivalent", 
instrument_type == "CMO" ~"Other Fi", 
instrument_type == "NON-SECY ASSET STOCK" ~"Other"))

如果对data.table类似于case_when的解决方案感兴趣,data.tablefcase可以在data.table的开发版本中找到。

最新更新