简体   繁体   English

替换R中冗长的ifelse结构的最佳方法

[英]Best way to replace a lengthy ifelse structure in R

I have the following data frame 我有以下数据框

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

I need to add another column tCode that gets calculated from Code column. 我需要添加从Code列中获取的另一列tCode Code has a wide range of values. Code具有广泛的价值。 For each given range, I need to have a specific value for tCode . 对于每个给定范围,我需要为tCode设置一个特定值。 I can't use cut function for example for this task. 例如,我不能使用cut功能来完成此任务。 The range and the expected outcome are given to me. 范围和预期结果已提供给我。 I can only think of this lengthy ifelse structure: 我只能想到这个冗长的ifelse结构:

  df$tCode = ifelse(df$Code > 102, 81, 
                            ifelse(df$Code %in% seq(101,102,1),80,
                                   ifelse(df$Code %in% seq(99,100,1),79,
                                          ifelse(df$Code %in% seq(97,89,1),78,
                                                 ifelse(df$Code %in% seq(95,96,1),77,
                                                        ifelse(df$Code %in% seq(92,94,1),76,
                                                               ifelse(df$Code %in% seq(90,91,1),75,
                                                                      ifelse(df$Code %in% seq(88,89,1),74,
                                                                             ifelse(df$Code %in% seq(86,87,1),73,
                                                                                    ifelse(df$Code %in% seq(84,85,1),72,
                                                                                           ifelse(df$Code %in% seq(82,83,1),71,
                                                                                                  ifelse(df$Code %in% seq(80,81,1),70,1))))))))))))

I don't feel that this is the best way to solve this problem. 我认为这不是解决此问题的最佳方法。 Are there better suggestions?. 有更好的建议吗?

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"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM