mardi 24 mai 2016

R - Choose previously what are the elements to access

I have this doubt (but not only) in R.

Suppose we have the following data frame:
hot.people <- data.frame(language = c("Java", "PHP", "Python", "C++", "R", "C", "Haskell"), programmer = c("John", "Alice", "Jessica", "Peter", "Harry", "Anthony", "Phillip"), stringsAsFactors = FALSE)

We need to do, for each record, a processing between that and the next one or the following ones. This task is realized based on a condition.

For example, it can do it:

only.consecutive<-TRUE

sapply(1:(nrow(hot.people)-1), function(x, only=only.consecutive)
{
    if(only)
    {
        print(hot.people[x,])
        print(hot.people[x+1,])
    }
    else
    {
        print(hot.people[x,])
        print(hot.people[(x+1):nrow(hot.people),])
    }
})

What is desirable was to avoid the if instruction (and preferably to avoid a function to each situation). I know it is complicated because the x variable is inside of sapply, but it could be run something like:

FLAG<-...

sapply(1:(nrow(hot.people)-1), function(x, f=FLAG) {
    print(hot.people[x,])
    print(hot.people[f,])
})

Thanks for a solution.

Aucun commentaire:

Enregistrer un commentaire