简体   繁体   中英

Get indeces of columns based on a vector of names (in R)

I have a dataframe with named columns.

Let's assume:

> colnames(df)
[1] "apple"   "orange"   "banana"   "pear"   "melon"

I want to get the indices of the columns that match strings in a vector.

> myNames = c("apple","pear")
> foo(myNames,colnames(df))
[1] 1 4

Originally, which() and %in% came to mind but neither worked in my implementation due to the inputs being both vectors; examples for the sake of completeness:

> which(colnames(df) == myNames )
> myNames %in% colnames(df)

Any help on how to do this without a loop would be appreciated.

which and %in% are one option

x <- c("apple", "orange", "banana", "pear", "melon")
myNames = c("apple","pear")

which(x %in% myNames)
[1] 1 4

Another one is match

match(myNames, x)
[1] 1 4

You can use grep to find them one by one like this:

grep("apple",df)

or use this:

colno=function(vector,df){
  result=c()
  a=length(vector)

  for(i in 1:a){
    result[i]=grep(vector[i],colnames(df))}
  return(result)}

Then call it like,

colno(myNames,df)

Hope it helps

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