R将数据与因子和水平分组(R grouping data with factors and levels)

编程入门 行业动态 更新时间:2024-10-17 05:37:52
R将数据与因子和水平分组(R grouping data with factors and levels)

我对R很新。我只是在研究一个问题。

我正在尝试制作频率表。

说我有数据

X<-c(1,2,3,4,3,9, 20)

我想创建一个频率表,使其显示所有空单元格

(factor(X, levels = c(0:max(X))))

现在我想要用R做的是将它分组,所以级别实际上是0,1,2,3,4,5和> 5。

对此的任何建议都会很棒

I'm trying to make a frequency table that groups values into a limited number of bins.

Say I have the data

X <- c(1,2,3,4,3,9, 20)

I can make a frequency table such that it shows all the empty cells like this:

(factor(X, levels = c(0:max(X))))

Instead of showing the frequency of every possible value, I would like to bin values >5 so that the levels on the table are: 0, 1, 2, 3, 4, 5, and >5.

How can I do this?

最满意答案

首先需要转换向量以使其具有唯一条目,然后您可以在factor()函数中添加缺少的级别:

X <- c(1,2,3,4,3,9,20) X <- ifelse(X>5,">5",X) X <- factor(X,levels=c(0:5,">5"))

这导致:

X [1] 1 2 3 4 3> 5> 5级别:0 1 2 3 4 5> 5

You first need to transform the vector so that it has an unique entry for, then you can add the missing levels in the factor() function:

X <- c(1,2,3,4,3,9,20) X <- ifelse(X>5,">5",X) X <- factor(X,levels=c(0:5,">5"))

This results in:

X [1] 1 2 3 4 3 >5 >5 Levels: 0 1 2 3 4 5 >5

更多推荐

本文发布于:2023-07-26 00:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1268401.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:因子   水平   数据   grouping   factors

发布评论

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

>www.elefans.com

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