我的数据框的数字介于-1和+1之间。我想根据它们所处的范围将这些数字替换为低,中或高。
有没有办法使用ifelse条件创建函数,然后根据元素落在范围内的位置应用标签?
干杯,
答案 0 :(得分:1)
ifelse(variable < 0, "low", ifelse(variable < 1, "medium", "high"))
各种方法的计时:
variable <- data.frame(matrix(rnorm(1e5*6), ncol = 6))
tst2 <- system.time(cut(as.matrix(variable), breaks = c(-Inf, -1, 1, Inf), labels = c("low","medium","high")))
tst1 <- system.time(ifelse(variable < 0, "low", ifelse(variable < 1, "medium", "high")))
tst3 <- system.time(lapply(variable, cut, breaks=c(-Inf, -1, 1, Inf), labels=c("low", "medium", "high")))
> data.frame(tst1["elapsed"],tst2["elapsed"],tst3["elapsed"])
tst1..elapsed.. tst2..elapsed.. tst3..elapsed..
elapsed 0.46 0.15 0.17