Aubrée
Aubrée

Reputation: 31

sum of each column between them in R

I have a dataframe like this :

dd<-data.frame(col1=c(1,0,1),col2=c(1,1,1),col3=c(1,0,0),col4=c(1,0,1,0,1,0,1,0))

And i would like to have the sum of each column between them like:

col1+col2   col1+col3   col1+col4   col2+col3   col2+col4   col3+col4   
2            2          2          2          2            2
1            1          1          1          1            0
1            1          2          1          2            1
2            1          1          1          1            0

I did'nt find any fonctions who does that Please help me

Upvotes: 2

Views: 75

Answers (3)

hello_friend
hello_friend

Reputation: 5788

Uglier, and slower than the base R above:

do.call("cbind", setNames(Map(function(i){y <- dd[,i] + dd[,-c(1:i)]}, 
                              seq_along(dd)[1:ncol(dd)-1]), names(dd)[1:(ncol(dd)-1)]))

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 39858

One dplyr and purrr possibility could be:

map_dfc(.x = combn(names(dd), 2, simplify = FALSE),
        ~ dd %>%
         rowwise() %>%
         transmute(!!paste(.x, collapse = "+") := sum(c_across(all_of(.x)))))

  `col1+col2` `col1+col3` `col1+col4` `col2+col3` `col2+col4` `col3+col4`
        <dbl>       <dbl>       <dbl>       <dbl>       <dbl>       <dbl>
1           2           2           2           2           2           2
2           1           0           0           1           1           0
3           2           1           2           1           2           1

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101169

One base R option might be combn + rowSums

setNames(
  as.data.frame(combn(dd, 2, rowSums)),
  combn(names(dd), 2, paste0, collapse = "+")
)

which gives

  col1+col2 col1+col3 col1+col4 col2+col3 col2+col4 col3+col4
1         2         2         2         2         2         2
2         1         0         0         1         1         0
3         2         1         2         1         2         1

Data

dd<-data.frame(col1=c(1,0,1),col2=c(1,1,1),col3=c(1,0,0),col4=c(1,0,1))

Upvotes: 2

Related Questions