Best way to replace a lengthy ifelse structure in R

后端 未结 1 1529
栀梦
栀梦 2020-12-03 16:30

I have the following data frame

df = data.frame(Code=seq(80,105,1))

I need to add another column tCode that gets calculated fr

相关标签:
1条回答
  • 2020-12-03 17:11

    Come up with a matching table and merge.

    I'll do the first couple statements for brevity, hopefully you get the point:

    library(data.table); setDT(df)
    
    match_table <- 
      data.table(Code = c(89:102),
                 tCode = c(rep(78, 9), 79, 79, 80, 80))
    
    df[match.table, tCode := tCode, on = "Code"]
    
    0 讨论(0)
提交回复
热议问题