user9295444
user9295444

Reputation:

Merging two columns at once in R

I have a data frame with 127 columns and 518 rows. Now I have to odd and even columns (from 3).

>data
Name id S1 S2 S3 S4 S5 S6
abc  1  A  A  C  C  G  G
abc  2  A  G  T  T  C  G
abc  3  G  C  T  A  A  C

The output which I want is

>output
Name id S2 S4 S6  
abc  1  AA  CC  GG
abc  2  AG  TT  CG
abc  3  GC  TA  AC

Can anyone help me with this?

Upvotes: 1

Views: 46

Answers (1)

akrun
akrun

Reputation: 887118

We can use Map to do this after subsetting the alternate columns

res <- data.frame(data[1:2], Map(paste0, data[-(1:2)][c(TRUE, FALSE)], 
                  data[-(1:2)][c(FALSE, TRUE)]))
names(res)[3:5] <-  names(data)[3:8][c(FALSE, TRUE)]
res
#   Name id S2 S4 S6
#1  abc  1 AA CC GG
#2  abc  2 AG TT CG
#3  abc  3 GC TA AC

Upvotes: 3

Related Questions