xboxuser
xboxuser

Reputation: 160

Trying to compare two dataframes, and writing a logical result to a new dataframe in R

I have an R dataframe that contains 18 columns, I would like to write a function that compares column 1 to column 2, and if both columns contain the same value, a logical result of T or F is written to a new column (this part is not too hard for me), however I would like to repeat this process over for the next columns and write T/F to a new column.

values col 1 = values col 2, write T/F to new column, values col 3 = values col 4, write T/F to a new column (or write results to a new dataframe)

I have been trying to do this with the purrr package, and use the pmap/map function, but I know I am making a mistake and missing some important part.

Upvotes: 0

Views: 84

Answers (1)

jpshanno
jpshanno

Reputation: 261

This function should work if I understand your problem correctly.

df <- 
  data.frame(a = c(18, 6, 2 ,0), 
             b = c(0, 6, 2, 18), 
             c =  c(1, 5, 6, 8),
             d = c(3, 5, 9, 2))

compare_columns <- 
  function(x){
    n_columns <- ncol(x)
    odd_columns <- 2*1:(n_columns/2) - 1
    even_columns <- 2*1:(n_columns/2)
    comparisons_list <- 
      lapply(seq_len(n_columns/2),
             function(y){
               df[, odd_columns[y]] == df[, even_columns[y]]
             })
    comparisons_df <- 
      as.data.frame(comparisons_list,
                    col.names = paste0("column", odd_columns, "_column", even_columns))
    return(cbind(x, comparisons_df))
  }

compare_columns(df)

Upvotes: 1

Related Questions