从列中提取所有非零值
Extract all non zero values from a column
我有一个矩阵,其中 n 列具有零值和非零值:
A B C
1 3 0
2 4 0
0 0 3
我想从 c 列中提取所有非零值并将其分配给新的矩阵或数据框。我该怎么做?
m2 <- m
m2[m2[,3] == 0, 3] <- NA
m2
# A B C
# [1,] 1 3 NA
# [2,] 2 4 NA
# [3,] 0 0 3
m2[,3,drop = FALSE]
# C
# [1,] NA
# [2,] NA
# [3,] 3
数据
m <- structure(c(1L, 2L, 0L, 3L, 4L, 0L, 0L, 0L, 3L), .Dim = c(3L, 3L), .Dimnames = list(NULL, c("A", "B", "C")))
我有一个矩阵,其中 n 列具有零值和非零值:
A B C
1 3 0
2 4 0
0 0 3
我想从 c 列中提取所有非零值并将其分配给新的矩阵或数据框。我该怎么做?
m2 <- m
m2[m2[,3] == 0, 3] <- NA
m2
# A B C
# [1,] 1 3 NA
# [2,] 2 4 NA
# [3,] 0 0 3
m2[,3,drop = FALSE]
# C
# [1,] NA
# [2,] NA
# [3,] 3
数据
m <- structure(c(1L, 2L, 0L, 3L, 4L, 0L, 0L, 0L, 3L), .Dim = c(3L, 3L), .Dimnames = list(NULL, c("A", "B", "C")))