How to merge multiples columns of a table into 1 in R -
i have data frame (control.sub
) containing multiple columns (t1,t2,t3,t4,t5,t6
). want merge these columns one, na should removed.
> control.sub t1 t2 t3 t4 29 5500024017802120306174.h01 5500024017802120306174.g02 5500024017802120306174.e03 5500024017802120306174.d04 810 5500024030401071707292.h01 5500024030401071707292.g02 5500024030401071707292.e03 5500024030401071707292.d04 4693 5500024035736031208612.g08 5500024035736031208612.e09 5500024035736031208612.d10 5500024035736031208612.b11 t5 t6 29 5500024017802120306174.b05 5500024017802120306174.a06 810 5500024030401071707292.b05 5500024030401071707292.a06 4693 5500024035736031208612.a12 <na>
i want final outcome as:
> control.sub t1 29 5500024017802120306174.h01 5500024017802120306174.g02 5500024017802120306174.e03 5500024017802120306174.d04 810 5500024030401071707292.h01 5500024030401071707292.g02 5500024030401071707292.e03 5500024030401071707292.d04 4693 5500024035736031208612.g08 5500024035736031208612.e09 5500024035736031208612.d10 5500024035736031208612.b11 5500024017802120306174.b05 5500024017802120306174.a06 5500024030401071707292.b05 5500024030401071707292.a06 5500024035736031208612.a12
one columns (t1) containing values.
slightly more reproducible example:
df <- data.frame(t1 = c(letters[1:5],na), t2 = c(na, letters[6:10]), t3 = c(11:12,na,13:15), stringsasfactors=false) df # t1 t2 t3 # 1 <na> 11 # 2 b f 12 # 3 c g na # 4 d h 13 # 5 e 14 # 6 <na> j 15 df2 <- data.frame(t1 = apply(df, 1, function(s) paste(s[!is.na(s)], collapse=" ")) ) df2 # t1 # 1 11 # 2 b f 12 # 3 c g # 4 d h 13 # 5 e 14 # 6 j 15
edit
i think op looking this, his/her example wrong:
unlist_not_na <- function(df){ v <- unlist(df) v[!is.na(v)] } df3 <- data.frame(t1 = unlist_not_na(df)) df3 # t1 # t11 # t12 b # t13 c # t14 d # t15 e # t22 f # t23 g # t24 h # t25 # t26 j # t31 11 # t32 12 # t34 13 # t35 14 # t36 15
Comments
Post a Comment