Loop over rows of dataframe applying function with if-statement

前端 未结 3 515
攒了一身酷
攒了一身酷 2020-12-13 02:16

I\'m new to R and I\'m trying to sum 2 columns of a given dataframe, if both the elements to be summed satisfy a given condition. To make things clear, what I want to do is:

3条回答
  •  情歌与酒
    2020-12-13 03:00

    I'll chip in and provide yet another version. Since you want zero if the condition doesn't mach, and TRUE/FALSE are glorified versions of 1/0, simply multiplying by the condition also works:

    t.d<-as.data.frame(matrix(1:9,ncol=3))
    t.d <- within(t.d, V4 <- (V1+V3)*(V1>1 & V3<9))
    

    ...and it happens to be faster than the other solutions ;-)

    t.d <- data.frame(V1=runif(2e7, 1, 2), V2=1:2e7, V3=runif(2e7, 5, 10))
    system.time( within(t.d, V4 <- (V1+V3)*(V1>1 & V3<9)) )         # 3.06 seconds
    system.time( ifelse((t.d$V1>1)&(t.d$V3<9), t.d$V1+ t.d$V3, 0) ) # 5.08 seconds
    system.time( { t.d <- within(t.d, V4 <- V1 + V3); 
                   t.d[!(t.d$V1>1 & t.d$V3<9), "V4"] <- 0 } )       # 4.50 seconds
    

提交回复
热议问题