将值分配到特定范围

编程入门 行业动态 更新时间:2024-10-23 21:34:03
本文介绍了将值分配到特定范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个简单的问题要弄清楚:

I have an easy question to figure out:

value 1000 2500 5080 10009

我要指定值到一个间隔:

value Range 1000 0-1000 2500 1001-5000 5080 5001-10000 10009 10001-20000

我尝试以下操作:

dt[, Range := ifelse(value < 1001, "0-1000", ifelse(1000 < value < 5001, "1001-5000", ifelse(5000 < value < 10001, "5001-10000", "10001-20000")))

但是,我得到了错误: dt [中出现意外的'<',范围:= ifelse(值< 1001, 0-1000,ifelse (1000< value<

有什么帮助吗?

编辑:

这个问题并不是在寻求将连续变量转换为因子的最佳方法,而是在寻求可重现示例的调试帮助:

This question is not asking for the best way to convert a continuous variable to a factor. It is asking for debugging help with the reproducible example:

library(data.table) dt <- data.table(value = c(1000, 2500, 5080, 10009)) dt[, Range := ifelse(value < 1001, "0-1000", ifelse(1000 < value < 5001, "1001-5000", ifelse(5000 < value < 10001, "5001-10000", "10001-20000"))) # produces the error above

推荐答案

)错误,则表示其含义。与python不同,R无法解释 1000<值< 5001 。相反,您需要使用 1000<价值和值< 5001

Like many (some) errors, it means what it says. Unlike python, R can't interpret 1000 < value < 5001. Instead you need to use 1000 < value & value < 5001

library(data.table) dt <- data.table(value = c(1000, 2500, 5080, 10009)) dt[, Range := ifelse(value < 1001, "0-1000", ifelse(1000 < value & value < 5001, "1001-5000", ifelse(5000 < value & value < 10001, "5001-10000", "10001-20000")))] dt value Range 1: 1000 0-1000 2: 2500 1001-5000 3: 5080 5001-10000 4: 10009 10001-20000

正如@akrun提到的那样,您可能会有一个更好的选择。例如:

As @akrun mentioned, you may be better off with a factor. Here's an example:

dt[, Range := cut(value, breaks = c(0, 1001, 5001, 10001, 20001), labels = c("0-1000", "1001-5000", "5001-10000", "10001-20000"))]

这会产生一个显示相同方式的data.table,但是提取 Range 列将为您提供一个与范围。

This produces a data.table that displays the same way, but extracting the Range column will give you a factor corresponding to the ranges.

更多推荐

将值分配到特定范围

本文发布于:2023-11-30 01:19:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648238.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分配

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!