Combining more than 2 columns by removing NA's in R

前端 未结 3 2177
说谎
说谎 2020-12-06 07:28

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

3条回答
  •  渐次进展
    2020-12-06 08:12

    You can use apply for this. If df is your dataframe`:

    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
    

提交回复
热议问题