繁体   English   中英

根据R中多列的值将连续变量分为2个因子

[英]Making continuous variables into 2 factors based on value for multiple columns in R

我有一个40列以上的数据框。 我想做一些我认为cut可以做的非常简单的事情:将我的所有值更改为2个因子,对于列3:38,将那些<10和> 10的值分别设置为“ 0”或“ 1”。 我尝试使用cut,但出现错误:

'data.frame':   182 obs. of  38 variables:
 $ col_names                           : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Case_control                        : Factor w/ 2 levels "0","1": 2 1 1 2 2 2 2 2 2 2 ...
 $ Sample_1_fung               : int  0 0 5 0 0 0 0 0 0 0 ...

我试过了

test_cat <- lapply(qpcr180_df[,3:38],cut, breaks=2,by=10, quantile=F)
Error in cut.default(X[[20L]], ...) : 'breaks' are not unique
> 

并且:当我执行test_cat <- lapply(qpcr180_df[,3:38],cut, breaks=2*(-1:9), quantile=F, labels=2*(0:9))

我得到一张表,该表中的因子被标记为2-12和NA,而不是<10一个标签和>10一个标签。

任何帮助表示赞赏!

您可以尝试:

set.seed(42)
dat1 <- as.data.frame(matrix(sample(1:20,5*4, replace=TRUE), ncol=5))
dat2 <- dat1
dat2[] <- cut(as.matrix(dat1),breaks=c(-Inf,10,Inf),labels=c('0','1'))
dat2
#   V1 V2 V3 V4 V5
#1  1  1  1  1  1
#2  1  1  1  0  0
#3  0  1  0  0  0
#4  1  0  1  1  1

dat1
#  V1 V2 V3 V4 V5
#1 19 13 14 19 20
#2 19 11 15  6  3
#3  6 15 10 10 10
#4 17  3 15 19 12

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM