At first sight this seems a duplicate of Combine/merge columns while avoiding NA? but in fact it isn\'t. I am dealing sometimes with more than two columns instead of just tw
You can use apply for this. If df is your dataframe`:
apply
df2 <- apply(df,1,function(x) x[!is.na(x)]) df3 <- data.frame(t(df2)) colnames(df3) <- colnames(df)[1:ncol(df3)]
Output:
# col1 col2 # 1 13 # 10 18 # 7 15 # 4 16