[R] names not inherited in functions

david dav davamaillist at gmail.com
Thu Jun 7 00:27:30 CEST 2007


Dear all,

I 'd like to keep the names of variables when calling them in a function.
An example might help to understand my problem :

The following function puts in a new data frame counts and percent of
a data.frame called as "tablo"
the step " nom.chiffr[1] <- names(vari) " is useless as names from the
original data.frame aren't kept in the function environement.

Hoping I use appropriate R-vocabulary, I thank you for your help

David

descriptif <- function (tablo) {
	descriptifvar <- function (vari) {
		table(vari)
		length(vari[!is.na(vari)])
		chiffr <- cbind(table(vari),100*table(vari)/(length(vari[!is.na(vari)])))
		nom.chiffr <- rep(NA, dim(table(vari)))
		if (is.null(names(vari))) nom.chiffr[1] <- paste(i,"") else
		nom.chiffr[1] <- names(vari)
		chiffr <- data.frame (  names(table(vari)),chiffr)
		rownames(chiffr) <- NULL
		chiffr <- data.frame (nom.chiffr, chiffr)
	return(chiffr)
	}
	
	res <- rep(NA, 4)
	for (i in 1 : ncol(tablo))
		res <- rbind(res,descriptifvar(tablo[,i]))
	colnames(res) <- c("variable", "niveau", "effectif", "pourcentage")
return(res[-1,])
}	
# NB I used this function on a data.frame with only factors in



More information about the R-help mailing list