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

Advertisements

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?

>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)

Leave a ReplyCancel reply