r - substract subset of data frame from the same data frame -


i have data frame of following structure: have ana number of rows , columns

v<-c("control", na, 1, 2, 4, "test", na, 1, 2, 4, "test", na, 1, 2, 4, "test", na, 1, 2, 4) df<- as.data.frame(t(matrix(v, nrow=5, ncol=4))) colnames(df)<-c("id", "g1", "g2", "g3", "g4") df        id   g1 g2 g3 g4 1 control <na>  1  2  4 2    test <na>  1  2  4 3    test <na>  1  2  4 4    test <na>  1  2  4 

i subtract rows id==control other rows, giving me following result:

result            id   g1 g2 g3 g4     1    test <na>  0  0  0     2    test <na>  0  0  0     3    test <na>  0  0  0 

i tried sweep() function, tried putting through loops, nothing worked.

it amazing if me. thank you!

assuming there single "control", create logical index based on 'control' value ('i1'), subset 'df' 'id' not 'control' ('df1'), use map subtract columns in 'df1' same columns 'id' 'control' , assign output corresponding columns in 'df1'.

i1 <- df$id=="control" df1 <- df[!i1,] df1[3:5] <- map(`-`, df1[3:5], df[i1,3:5]) df1 #    id   g1 g2 g3 g4 #2 test <na>  0  0  0 #3 test <na>  0  0  0 #4 test <na>  0  0  0 

or instead of using map can replicate make lengths equal both datasets , subtraction

df1[3:5] <- df1[3:5] - df[i1, 3:5][col(df1[3:5])] 

data

df[-(1:2)] <- lapply(df[-(1:2)], function(x) as.numeric(as.character(x))) 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -