creating new coloumns in a dataframe using for loop

I want to run this code multiple times, for all coloumn matching options, with ney colnames :

adatok <- adatok %>%
mutate(egyesült = Gene1 + 2*Gene2

the dataframe:
Sample Gene1 Gene2 Gene2.1 Gene4
1 ID1 1 1 0 0
2 ID2 0 0 0 1
3 ID3 0 0 0 1
4 ID4 1 0 0 0
5 ID5 1 1 0 1
6 ID6 0 0 0 1

#Thanks for help

I can't be sure what his means... ?

One interpretation of what you provided might be that you want to add and multiple with the form x+2*y for every possible pair of Gene column.

library(tidyverse)
start_df <- read_delim(file=
"Sample Gene1 Gene2 Gene2.1 Gene4
ID1 1 1 0 0
ID2 0 0 0 1
ID3 0 0 0 1
ID4 1 0 0 0
ID5 1 1 0 1
ID6 0 0 0 1")

(genenames<-names(select(start_df,-Sample)))


(genename_pairs <- combn(genenames,2,simplify=FALSE))

#before proceeding check that you are comfortable calculating this many variables 
2*choose(length(genenames),2)

( calced_df <- map_dfc(genename_pairs,\(pair_){
  transmute(start_df,
         "{pair_[1]}_{pair_[2]}":=!!sym(pair_[1]) + 2*!!sym(pair_[2]),
         #because x+2*y is not symetric we should do y+2*x also
         "{pair_[2]}_{pair_[1]}":=!!sym(pair_[2]) + 2*!!sym(pair_[1])
         )
  
  }))

(end_df <- bind_cols(start_df,calced_df))
2 Likes

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.