0

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.

4

2 回答 2

1

这可以向量化:

logicalVector <- x[3]=="B"
negativeVector <- c(1,-1)[logicalVector+1]
x[4] <- x[4}*negativeVector
于 2013-09-02T18:14:27.863 回答
0

您不需要apply这里的功能(只需使用ifelse):

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

使用 R 中的 iris 数据进行测试:

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
于 2013-09-02T18:13:53.260 回答