Enjoy R

A tool which is often left aside : the class person

The class person is useful to keep information like name and email address about one person or a group of.

Some problem arose to me when I tried to convert an object of this class to a well-specified data frame.

So, I implemented a function that should give a good output (it looks good to me, at least).
Following, the code and an example which shows how it works.

# the code

person2dataf <- function(person.element) {

    df <- sapply(unique(names(unlist(person.element))), function(x) 
        eval(parse(text = paste0(deparse(substitute(person.element)), "$", x))))

    mode(df) <- "character"

    for (i in 1:nrow(df)) for (j in 1:ncol(df)) {
        if (df[i, j] == "NULL") 
            df[i, j] <- NA
    }

    return(as.data.frame(df))
}

# an example

person.list <- person(given = list("Charles", "dav1d00", "Giacomo"), family = list("Baudelaire", 
    "", "Leopardi"), email = list("", "XXXYYY@gmail.com", ""), role = list(NULL, 
    "aut", NULL), comment = list("French poet", "it's me", "Italian poet"))

person.list

## [1] "Charles Baudelaire (French poet)"          
## [2] "dav1d00 <XXXYYY@gmail.com> [aut] (it's me)"
## [3] "Giacomo Leopardi (Italian poet)"

# applying the function

person2dataf(person.list)

##     given     family      comment role            email
## 1 Charles Baudelaire  French poet <NA>             <NA>
## 2 dav1d00       <NA>      it's me  aut XXXYYY@gmail.com
## 3 Giacomo   Leopardi Italian poet <NA>             <NA>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: