Subtract even columns from odd ones in a data frame

  • A+

I have a dataframe (in reality I have 170 columns (85 pairs) and ~8000 rows)

data <- data.frame(A = c(6,5,4,3), B = c(2,2,2,2), C = c(9,8,7,6), D = c(2,2,2,2)) 

I would like to subtract column 2 from column 1, column 4 from column 3, etc. for all rows.

I think I need to either try to write a function or use apply in some way.


You can choose every other column with c(TRUE,FALSE) or its negation. The binary-minus has a dataframe method:

data[c(TRUE,FALSE)] - data[c(FALSE,TRUE)]   A C 1 4 7 2 3 6 3 2 5 4 1 4 

If you wanted to name then meaningfull you could use paste on the names:

 paste( names(data[c(TRUE,FALSE)]) , "_minus_", names( data[c(FALSE,TRUE)]) ) 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: