[R] R Function to extract columnNames

arun smartpink111 at yahoo.com
Wed May 1 22:01:02 CEST 2013


Hi ST,

You could try this:
library(plyr)
set.seed(25)
mydf<- data.frame(subid=rep(1:5,each=3),Col=sample(c(0:5,NA),15,replace=TRUE))
retsample <- function(df, Column,size) {
set.seed(1234)
mysel <- ddply(df, .(subid),function(x) summarize(x,missing=sum(is.na(x[[Column]])|x[[Column]]==0)))
myids<- mysel[mysel$missing==0,1]
sample_regular<- subset(df,subid%in% sample(myids,size,replace=TRUE))    
return(sample_regular)
  }
retsample(mydf,"Col",5)
#   subid Col
#1      1   2
#2      1   4
#3      1   1
#10     4   1
#11     4   2
#12     4   2


A.K.



>Thanks David for the tip. I dont think I still have this working for a 
function that i am writing. Say col, subid are column names in my 
dataframe >mydf. My calling function is retsample(mydf,"Col",5) 
>This below function fails in ddply call. In this call I am counting 
how many nulls or zeros exist for that colum that I am passing. I get 
"Error in >eval(expr, envir, enclos) : object 'myCol' not found" 
>
>#Get appropriate random sample to print for variable col from dataframe df, that has 0 missing values 
>retsample <- function(df,x,size ) { 
 >     set.seed(1234) 
  >    myCol <- df[[x]] 
  >    mysel <- ddply(df,c("subid"),summarise,missing=sum(is.na(myCol)| myCol==0)) 
  >    #select subjects with no missing values 
  >    myids <- mysel[mysel$missing==0,1] 
  >    sample_regular <- subset(df,subid %in% sample(myids, size=size)) 
  >    return(sample_regular) 
>} 
>
>Thank You for your assistance. 
>-ST 




----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: R help <r-help at r-project.org>
Cc: 
Sent: Tuesday, April 30, 2013 9:00 AM
Subject: Re: R Function to extract columnNames

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