[R] R Function to extract columnNames

David Winsemius dwinsemius at comcast.net
Tue Apr 30 17:47:41 CEST 2013


On Apr 30, 2013, at 6:00 AM, arun wrote:

> Hi,
> May be this helps:
> funcName<- function(df1, x){
>  whatCol=df1[[x]]
>  print("Got it")
>  print(whatCol)
>  }
>  
> funcName(df,"ColA")
> #[1] "Got it"
> #[1] 1 2 3 4 5
>   funcName(df,"ColB")
> #[1] "Got it"
> #[1] A B C D E
> #Levels: A B C D E
> 
> 

To ST;

You should now realize that this function has already been built into R and its name is "[[".

The "$" function is just variation on "[[" that does not evaluate its argument. You effort to parse back to  paste("df",x,sep="$") failed, but might have succeeded if you took this route:

eval(parse(text= paste("df",x,sep="$") ) )

I'm not saying you should have done that since obviously "[[" is the proper, approved, economical way to do it. I'm just trying to get you to understand the language better. You should spend further time with:

help("Extract")    # to cement this lesson and extend your understanding.

-- 
David.

> A.K.
> 
> 
>> I am trying to extract the 2nd column from a dataframe using a function 
> called funcName. Note this is an example that I need cos I am using it 
> to >read the values I pass into a function call - these passed values 
> represent dataframe column names. I am trying to use this concept for a 
> vary large >dataframe with 100+ columns. 
>> 
>> ColA <- c(1,2,3,4,5) 
>> ColB <- c("A","B","C","D","E") 
>> df <- data.frame(ColA,ColB) 
>> 
>> funcName <- function(x) { 
>> whatCol = paste("df",x,sep="$") 
>  >print("Got it",whatCol) 
>> } 
>> 
>> funcName("ColA") 
>> 
>> Please advise, since this code is not working. Thanks in advance. 
>> 
>> -ST
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list