简体   繁体   English

在矩阵中将NA的矩阵转换为0并将连续变量转换为1

[英]converting a matrix of NAs to 0s and continous variables to 1s in a matrix

I have a matrix populated with NAs and continuous values. 我有一个矩阵,其中填充了NA和连续值。 I need to convert NAs to 0s and continuous values to 1s. 我需要将NA转换为0,并将连续值转换为1。 How can I do this in R? 我如何在R中做到这一点?

Assuming m is as in the Note at the end: 假设m如结尾处的注释所示:

1 - is.na(m)
##      [,1] [,2]
## [1,]    0    1
## [2,]    1    0

Note 注意

m <- matrix(c(NA, 2, 3, NA), 2)
m
##      [,1] [,2]
## [1,]   NA    3
## [2,]    2   NA

Use the ifelse function: 使用ifelse函数:

your_matrix <- matrix(c(NA,NA,NA,3.5,2.5,5.0), nrow=2)
your_matrix <- ifelse(is.na(your_matrix), 0, 1)

If you have some values in a vector (d) and you have a matrix (m), then converting the numeric values to 1's and the NA values to 0's can be done with two lines of code. 如果向量中有一些值(d),矩阵(m),则可以用两行代码将数值转换为1,将NA值转换为0。

d <- c(NA, NA, 2, 5, NA, 6, NA, 1,  6)
m <- matrix(data = d, nrow = 3, ncol = 3 )


m[is.na(d)] <- 0
m[d > 0 ] <- 1
m


#A matrix:
3 × 3 of 
type dbl
0 1 0
0 0 1
1 1 1

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

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