gpt4 book ai didi

r - 为数据框选择多个奇数或偶数列/行

转载 作者:行者123 更新时间:2023-12-01 16:06:36 29 4
gpt4 key购买 nike

R中有没有办法选择许多不连续的行/列,即奇数或偶数行/列?

我正在绘制主成分分析的载荷。我有 84 行数据,如下所示: x_1 y_1 x_2..... x_42 y_42

目前我正在为 x 和 y 载荷数据创建数据框,如下所示:

data.pc = princomp(as.matrix(data))

x.loadings <- data.frame(x=data.pc$loadings[c(1, 3, 5, 7, 9, 11, 13 ,15, 17, 19,
21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41), 1])

yloadings <- data.frame(y=data.pc$loadings[c(2, 4, 6, 8, 10, 12, 14, 16, 18, 20,
22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42), 1])

肯定有更简单的方法吗?

最佳答案

当逻辑向量用于索引时,它们会被回收,因此这会得到奇数列或奇数行

 calld[ c(TRUE,FALSE), ]  # rows
calld[ , c(TRUE,FALSE) ] #columns

偶数行或偶数列:

 calld[ !c(TRUE,FALSE), ]  # rows
calld[ , !c(TRUE,FALSE) ] #columns

每隔三列:

  calld[ , c(TRUE,FALSE, FALSE) ]   #columns 1,4,7 , ....

最近的评论者声称这不再有效。我在 Ubuntu 中运行的 R 4.0.4 中没有发现这一点:

> d <- data.frame(as.list(1:10))  # simple example construction
> d
X1L X2L X3L X4L X5L X6L X7L X8L X9L X10L
1 1 2 3 4 5 6 7 8 9 10
> d[, c(TRUE,FALSE)]
X1L X3L X5L X7L X9L
1 1 3 5 7 9
> d[, c(TRUE,FALSE,FALSE)] # example: # of columns not exact multiple of length of logical vector
X1L X4L X7L X10L
1 1 4 7 10

关于r - 为数据框选择多个奇数或偶数列/行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24440258/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com