如何将大于阈值的值转换为 R 中矩阵列中的 1?
要将 R 数据帧中矩阵中大于阈值的值转换为 1,我们可以按照以下步骤操作 -
首先,创建一个矩阵。
然后,使用 ifelse 函数将大于阈值的值转换为 1。
示例
创建矩阵
让我们创建一个矩阵,如下所示 -
M<-matrix(rnorm(50),ncol=2)输出结果M
执行时,上述脚本生成以下内容output(this output will vary on your system due to randomization)-
[,1] [,2][1,] 1.35131510 1.37522054
[2,] -1.13345162 0.36286206
[3,] 0.63015182 -0.03290929
[4,] 0.92621651 1.31680036
[5,] -0.82421679 0.32648195
[6,] 0.97343371 -1.07267437
[7,] 1.64987699 -0.78395936
[8,] -1.26893096 -0.86729417
[9,] 1.43618275 -0.35711054
[10,] 0.47313589 1.33716595
[11,] -0.62682302 -0.11872530
[12,] -1.55459406 0.60669510
[13,] 0.71674609 0.38263617
[14,] 0.15818009 0.40835948
[15,] -0.63320156 -0.06941598
[16,] -0.18245803 -0.69972541
[17,] -0.83207399 -2.18994824
[18,] -0.50880490 -1.11029099
[19,] 0.09978232 0.84119858
[20,] -0.53728939 -0.42712942
[21,] 0.78737850 0.64063631
[22,] -0.54197740 1.52800265
[23,] 0.64130714 0.03383875
[24,] 0.54300424 -0.48200610
[25,] -0.91642041 -0.27952213
将大于阈值的值转换为 1
使用 ifelse 函数将大于阈值的值转换为矩阵 M 的第 1 列中的 1 -
M<-matrix(rnorm(50),ncol=2)输出结果M[,1]<-ifelse(M[,1]>0.5,1,M[,1])
M
[,1] [,2][1,] 1.00000000 1.37522054
[2,] -1.13345162 0.36286206
[3,] 1.00000000 -0.03290929
[4,] 1.00000000 1.31680036
[5,] -0.82421679 0.32648195
[6,] 1.00000000 -1.07267437
[7,] 1.00000000 -0.78395936
[8,] -1.26893096 -0.86729417
[9,] 1.00000000 -0.35711054
[10,] 0.47313589 1.33716595
[11,] -0.62682302 -0.11872530
[12,] -1.55459406 0.60669510
[13,] 1.00000000 0.38263617
[14,] 0.15818009 0.40835948
[15,] -0.63320156 -0.06941598
[16,] -0.18245803 -0.69972541
[17,] -0.83207399 -2.18994824
[18,] -0.50880490 -1.11029099
[19,] 0.09978232 0.84119858
[20,] -0.53728939 -0.42712942
[21,] 1.00000000 0.64063631
[22,] -0.54197740 1.52800265
[23,] 1.00000000 0.03383875
[24,] 1.00000000 -0.48200610
[25,] -0.91642041 -0.27952213
以上是 如何将大于阈值的值转换为 R 中矩阵列中的 1? 的全部内容, 来源链接: utcz.com/z/361970.html