Q:

Merging columns within a dataframe for variable number of columns in r

I have a data frame as below. I would like to merge columns from V2 onwards (pref with a common between) but exclude the NAs in the merged column. There are variable amounts of columns with NAs in each row. 
V1                          V2    V3        V4     V5       V6         V7    
chr11:69464719-69502928    CCND1 ORAOV1     NA     NA       NA         NA     
chr7:55075808-55093954     EGFR    NA       NA     NA       NA         NA     
chr3:169389459-169490555   TERC   ARPM1     NA     NA       NA         NA     
chr1:150496857-150678056   ENSA   MCL1   ADAMTSL4 GOLPH3L   HORMAD1  MIR4257

The result I would like is:
V1                          V2
chr11:69464719-69502928    CCND1,ORAOV1
chr7:55075808-55093954     EGFR
chr3:169389459-169490555   TERC,ARPM1
chr1:150496857-150678056   ENSA,MCL1,ADAMTSL4,GOLPH3L,HORMAD1,MIR4257

I know how to concatenate fixed columns but the variable columns with exclusion of NA has thrown me. 

A:

We could loop over the rows using apply with MARGIN=1 (excluding the 1st column), paste the non-NA elements (toString is a wrapper for paste(., collapse=', '))  
V2 <- apply(df1[-1],1, function(x) toString(x[!is.na(x)]))
res <- data.frame(V1=df1[,1], V2, stringsAsFactors=FALSE)
res
#                       V1                                              V2
#1  chr11:69464719-69502928                                   CCND1, ORAOV1
#2   chr7:55075808-55093954                                            EGFR
#3 chr3:169389459-169490555                                     TERC, ARPM1
#4 chr1:150496857-150678056 ENSA, MCL1, ADAMTSL4, GOLPH3L, HORMAD1, MIR4257

Or using melt from data.table, convert the dataset to long form, group by 'V1' and paste the elements of 'value' column.  Initially, we convert 'data.frame' to 'data.table' using setDT. 
library(data.table)
melt(setDT(df1), id.var='V1', na.rm=TRUE)[, list(V2=toString(value)) , V1]
#                        V1                                              V2
#1:  chr11:69464719-69502928                                   CCND1, ORAOV1
#2:   chr7:55075808-55093954                                            EGFR
#3: chr3:169389459-169490555                                     TERC, ARPM1
#4: chr1:150496857-150678056 ENSA, MCL1, ADAMTSL4, GOLPH3L, HORMAD1, MIR4257

data
df1 <- structure(list(V1 = c("chr11:69464719-69502928", 
"chr7:55075808-55093954", 
"chr3:169389459-169490555", "chr1:150496857-150678056"),
V2 = c("CCND1", 
"EGFR", "TERC", "ENSA"), V3 = c("ORAOV1", NA, "ARPM1", "MCL1"
), V4 = c(NA, NA, NA, "ADAMTSL4"), V5 = c(NA, NA, NA, "GOLPH3L"
), V6 = c(NA, NA, NA, "HORMAD1"), V7 = c(NA, NA, NA, "MIR4257"
)), .Names = c("V1", "V2", "V3", "V4", "V5", "V6", "V7"), 
class = "data.frame", row.names = c(NA, -4L))

