Stijn
Stijn

Reputation: 551

Error when applying function by factor in dataframe

I have a dataframe consisting of four columns. The third is a factor variable, with levels A and B, and the fourth variable is numeric. I want to flip the sign of the numeric variable if the corresponding factorlevel is B. So, given a row x of my dataframe, I want to do this:

negate <- function(x) { 
  if(x[3] == B) {
    x[4] <- -x[4]
  }
}

However, when I try

apply(dataframe,1,negate)

I get the following error:

Error in -x[4] : invalid argument to unary operator

How do I do what I want to do? Thanks in advance.

Upvotes: 0

Views: 127

Answers (2)

Ari B. Friedman
Ari B. Friedman

Reputation: 72731

This can be vectorized:

logicalVector <- x[3]=="B"
negativeVector <- c(1,-1)[logicalVector+1]
x[4] <- x[4}*negativeVector

Upvotes: 1

Metrics
Metrics

Reputation: 15458

You don't need the apply function here (just use ifelse) :

mydata$col4<-with(mydata,ifelse(col3=="B",-col4,col4))

Test using iris data from R:

mydata<-iris
mydata$Petal.Length<-with(mydata,ifelse(Species=="setosa",-Petal.Length,Petal.Length))
> mydata
    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1            5.1         3.5         -1.4         0.2     setosa
2            4.9         3.0         -1.4         0.2     setosa
3            4.7         3.2         -1.3         0.2     setosa
4            4.6         3.1         -1.5         0.2     setosa

Upvotes: 0

Related Questions