[R] R Function to extract columnNames

arun smartpink111 at yahoo.com
Tue Apr 30 15:00:28 CEST 2013


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


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



More information about the R-help mailing list