如何使用变量作为索引来对 R 中的数据帧进行子集化?

时间:2021-03-18 13:55:20

标签: r dataframe subset

我想弄清楚如何使用变量作为索引来对数据帧进行子集化。如果我使用数值,从数据框中选择我感兴趣的列没有任何问题:

m1 <- c(0.3,0.2,0.1,0.1,0.3,0)
m2 <- c(0.1,0.1,0.1,0.2,0.3,0.2)
m3 <- c(0.2,0.1,0.2,0.3,0.2,0)

input <- data.frame(m1,m2,m3)

# I select the first two columns
example <- input[,1:2]

输出是我所期望的:

   m1  m2
1 0.3 0.1
2 0.2 0.1
3 0.1 0.1
4 0.1 0.2
5 0.3 0.3
6 0.0 0.2

但是,如果我定义变量 m <- 1L 或类似 m<-1 并尝试提取列:

example2 <- input[,m:m+1]

输出为:

[1] 0.1 0.1 0.1 0.2 0.3 0.2

为什么?以及如何使用变量作为索引从数据框中选择列?

1 个答案:

答案 0 :(得分:0)

您需要将 m+1 括在括号中,以便在计算 1: 部分之前计算它。

原因如下:

> 1:2+1
[1] 2 3  #the numeric vactor 1:2, with the value of 1 added to it
> 1:(2+1) 
[1] 1 2 3 #the numeric vector 1:3
相关问题