简体   繁体   中英

How to use a variable as index to subset a dataframe in R?

I am trying to figure out how to use a variable as index to subset a dataframe. If I use numeric values I do not have any problem to select the columns I'm interested in from the dataframe:

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]

and the output is what I expect:

   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

However, if I define the variable m <- 1L or like m<-1 and I try to extract the columns:

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

The output is:

[1] 0.1 0.1 0.1 0.2 0.3 0.2

Why? And how to use a variable as index to select columns from a dataframe?

you need to wrap m+1 in parenthesis so its get calculated before the 1: part is evaluated.

here's why:

> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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