R - 使用sapply删除矩阵

时间:2017-09-09 23:06:06

标签: r sapply

我试图删除矩阵中常量的所有列,但收到此错误:

Error in X[, sapply(X, function(x) length(unique(x)) != 1)] : 
  (subscript) logical subscript too long

我不完全确定为什么会出现这个错误

示例

    X <- structure(c(143.3, 152.37, 138.74, 149.87, 103.21, 130.98, 151.21, 
103.34, 126.5, 86.87, 561.24, 633.21, 529.73, 621.18, 319.53, 
476.16, 620.08, 279.21, 416.97, 184.58, 25.97, 30.05, 17.14, 
37.7, 9.7, 15.9, 24.95, -1.84, 7.5, -9.95, 4.74, 14.32, 4.39, 
5.1, 5.46, 4.87, 7.21, 4.31, 3.77, 4.32, 22.47, 205.1, 19.29, 
25.96, 29.8, 23.74, 52.04, 18.6, 14.18, 18.66, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0), .Dim = c(10L, 8L), .Dimnames = list(c("1", "2", 
"3", "4", "5", "6", "7", "8", "9", "10"), c("dday0_10", "dday10_30", 
"dday30C", "prec", "prec_sq", "(Intercept)", "statear", "statede"
)))

X[,sapply(X,function(x) length(unique(x))!=1)]

> Error in X[, sapply(X, function(x) length(unique(x)) != 1)] : 
  (subscript) logical subscript too long

我喜欢将数据保存为矩阵格式的解决方案。

1 个答案:

答案 0 :(得分:1)

如果您需要以矩阵格式保存数据,请尝试以下操作:

X[,apply(X,2,function(x) length(unique(x))!=1)]

输出:

   dday0_10 dday10_30 dday30C  prec prec_sq
1    143.30    561.24   25.97  4.74   22.47
2    152.37    633.21   30.05 14.32  205.10
3    138.74    529.73   17.14  4.39   19.29
4    149.87    621.18   37.70  5.10   25.96
5    103.21    319.53    9.70  5.46   29.80
6    130.98    476.16   15.90  4.87   23.74
7    151.21    620.08   24.95  7.21   52.04
8    103.34    279.21   -1.84  4.31   18.60
9    126.50    416.97    7.50  3.77   14.18
10    86.87    184.58   -9.95  4.32   18.66