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
has a wide range of values. For each given range, I need to have a specific value for tCode
. I can't use cut
function for example for this task. The range and the expected outcome are given to me. I can only think of this lengthy ifelse
structure:
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"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.