简体   繁体   中英

Select column dataframe index R

I have a data frame df like this

1    2    3    4

A    B     C   A

where the colnames are {1,2,3,4}. I would like to select one of the column of the data frame according to an index that I set externally

colf <- as.numeric(mo)
fmo <- df[[colf]]

Many thanks,

First things first I don't recommend having numbers as column names. Saying that, this should help you out.

> df <- data.frame("1"="A","2"="B","3"="C")
> df
  X1 X2 X3
1  A  B  C
> df$X1 #Get column by name
[1] A
Levels: A
> df[,1] #Get first column
[1] A
Levels: A
>  

Treat the data frame as a matrix and index it using [row,column] notation, ie

fmo = df[,colf]

This will always get column number colf.

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