IGOR IGOR - 1 month ago 6
R Question

Select a consecutive range of data.frame columns using names of beginning and end columns

I am trying to subset the columns of a

data.frame
using the interval of column names.

For instance, the
data.frame
A
:

A
ID1 ID2 ID3
1 5 01901
2 5 01902


For example, I want create variable b with the columns of A:

b=A[,"ID2":"ID3"]



Error in "ID1":"ID3" : NA/NaN argument In addition: Warning messages:
1: In
[.data.frame
(A, , "ID1":"ID3") : NAs introduced by coercion 2:
In
[.data.frame
(A, , "ID1":"ID3") : NAs introduced by coercion


What I want how solution:

b
ID2 ID3
5 01901
5 01902


When I put the indexes of the columns, it works. But when I use the column name, as above, does not work.

Answer

Use c() function, then it works when using column names

> A <- data.frame(ID1=c(1,1),ID2=c(5,5),ID3=c(01901,01902))
> A
#   ID1 ID2  ID3
# 1   1   5 1901
# 2   1   5 1902

> b <- A[,c(2:3)]
> b
#   ID2  ID3
# 1   5 1901
# 2   5 1902

> b1 <- A[,c("ID2","ID3")]
> b1
#   ID2  ID3
# 1   5 1901
# 2   5 1902

> b2 <- A[,2:3]
> b2
#   ID2  ID3
# 1   5 1901
# 2   5 1902