[R] Obtaining variable's names from a list of variables
Marc Schwartz
marc_schwartz at me.com
Wed Aug 17 14:48:49 CEST 2011
On Aug 17, 2011, at 1:46 AM, Monsieur Do wrote:
> Say I have a list of variables,
>
> listVar <- list(age,sex)
>
> I am looking for a way to either
>
> 1- create a vector c("age","sex") from it, or
> 2- get the names one by one in a for loop such as these
>
> a) for (i in 1:length(listVar)) rownames(result)[i] <- ???
>
> b) for(i in listVar) print (variable's name)
>
>
> Any help much appreciated.
Based upon the way in which you created 'listVar', there really is not a way to recover the variable names, since they are not retained:
age <- 1:2
sex <- c("M", "F")
listVar <- list(age, sex)
> listVar
[[1]]
[1] 1 2
[[2]]
[1] "M" "F"
> names(listVar)
NULL
On the other hand, if you use:
listVar <- list(age = age, sex = sex)
> listVar
$age
[1] 1 2
$sex
[1] "M" "F"
> names(listVar)
[1] "age" "sex"
HTH,
Marc Schwartz
More information about the R-help
mailing list