Skip to content
Prev 322789 / 398503 Next

R Function to extract columnNames

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.
function that i am writing. Say col, subid are column names in my 
dataframe >mydf. My calling function is retsample(mydf,"Col",5)
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"
?> ? ? 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)
----- 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.
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.
?>print("Got it",whatCol)