R仅在存在时才修改列

时间:2018-01-25 19:57:54

标签: r dataframe

假设我有以下代码段:

  mainResult$Time <- formatTime(mainResult$Time, "DateAndTime")
  mainResult$SettleDate <- formatTime(mainResult$SettleDate, "DateAndTime")
  mainResult$IssueDate <- formatTime(mainResult$IssueDate, "DateAndTime")
  mainResult$Maturity <- formatTime(mainResult$Maturity, "DateAndTime")
  mainResult$Bid <- formatNumber(mainResult$Bid, "withDecimals")  
  mainResult$Ask <- formatNumber(mainResult$Ask, "withDecimals")  
  mainResult$AvgBid <- formatNumber(mainResult$AvgBid, "withDecimals")  
  mainResult$AvgAsk <- formatNumber(mainResult$AvgAsk, "withDecimals")  
  mainResult$BidYield <- formatNumber(mainResult$BidYield, "withDecimals")  
  mainResult$AskYield <- formatNumber(mainResult$AskYield, "withDecimals")  
  mainResult$BidSize <- formatNumber(mainResult$BidSize, "noDecimals")  
  mainResult$AskSize <- formatNumber(mainResult$AskSize, "noDecimals")
  mainResult$Coupon <- formatNumber(mainResult$Coupon, "withDecimals")

如果列存在,则每个formatTimeformatNumber只能 。有没有一种干净的方法可以执行此操作,而不会将每个语句都包装在if块中,以检查列是否存在?

2 个答案:

答案 0 :(得分:4)

这是一种可怕的编码方式。尝试使用更像这样的东西:

# start with a vector of column names and loop
dt_columns = c("Time", "SettleDate", "IssueDate", "Maturity")
for (col in dt_columns) {
   if (col %in% names(mainResult)) mainResults[[col]] = formatNumber(mainResult[[col]], "DateAndTime")
}
# you can repeat for your other cases

或者这个:

# intersect and lapply
dt_columns = c("Time", "SettleDate", "IssueDate", "Maturity")
dt_columns = intersect(names(mainResults), dt_columns)
mainResult[dt_columns] = lapply(mainResult[dt_columns], formatNumber, "DateAndTime")

答案 1 :(得分:3)

我可能首先将有关您要执行的转换的信息与执行转换的代码中的列分开。更像这样的东西

afterModel(user) {
  user.hasMany('videos').reload();
})