Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何将离散值范围的数值向量转换为因子?_R - Fatal编程技术网

R 如何将离散值范围的数值向量转换为因子?

R 如何将离散值范围的数值向量转换为因子?,r,R,我试图将一个离散值的数值向量转换成R中的一个因子 x <- c(1,2,3,4,8,9,10,88,89,90) 我还尝试使用cut,如下所示: y <- factor(x, levels = c(1:2, 3:4, 8:10, 88:90)) bins <- c(1,3,5,8,11,88,90) y <- cut(x, breaks = bins, right = F, include.lowest = T) table(y) 有没有办法将一系列数值转换成R中

我试图将一个离散值的数值向量转换成R中的一个因子

x <- c(1,2,3,4,8,9,10,88,89,90)
我还尝试使用cut,如下所示:

y <- factor(x, levels = c(1:2, 3:4, 8:10, 88:90))
bins <-  c(1,3,5,8,11,88,90)
y <- cut(x, breaks = bins, right = F, include.lowest = T)
table(y)
有没有办法将一系列数值转换成R中的系数?

删除未使用的级别:

# as per your code    
bins <-  c(1,3,5,8,11,88,90)
y <- cut(x, breaks = bins, right = FALSE, include.lowest = TRUE)
levels(y)
# [1] "[1,3)"   "[3,5)"   "[5,8)"   "[8,11)"  "[11,88)" "[88,90]"

# drop unused levels
y1 <- droplevels(y)
levels(y1)
#[1] "[1,3)"   "[3,5)"   "[8,11)"  "[88,90]"
#根据您的代码

library(dplyr)
case_when(x %in% 1:2 ~ 1, x %in% 3:4 ~ 2, x %in% 8:10 ~ 3, x%in% 88:90 ~ 4)

删除未使用的级别:
表(droplevels(y))
因子(findInterval(x,c(3,8,88))
?或者可能
级别
# as per your code    
bins <-  c(1,3,5,8,11,88,90)
y <- cut(x, breaks = bins, right = FALSE, include.lowest = TRUE)
levels(y)
# [1] "[1,3)"   "[3,5)"   "[5,8)"   "[8,11)"  "[11,88)" "[88,90]"

# drop unused levels
y1 <- droplevels(y)
levels(y1)
#[1] "[1,3)"   "[3,5)"   "[8,11)"  "[88,90]"
library(dplyr)
case_when(x %in% 1:2 ~ 1, x %in% 3:4 ~ 2, x %in% 8:10 ~ 3, x%in% 88:90 ~ 4)