Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I subtract values of each column of my dataframe from all other columns?

I have a simple datafrme

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)

And I want to have a new dataframe that will contain the results of subtraction of each column from all others, one by one. I assume that will do the job

result_df <- data.frame()

# Subtract each column from all the other columns
for (i in 1:ncol(df)) {
  column_diff <- apply(df[, -i], 2, function(x) df[, i] - x)
  result_df <- cbind(result_df, column_diff)
}

but what is the issue?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to cbind() you need to combine elements with the same number of columns. I think you could set up result_df like this:

result_df <- data.frame(matrix(nrow=3, ncol = 0))

Or it might be better to create a list of column-differences, then combine them:

cdiff <- function(i) apply(df[, -i], 2, function(x) df[, i] - x)
newcols <- lapply(1:ncol(df), cdiff)
data.frame(newcols)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading