Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

na

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 two.

My dataframe looks like this:

     col1 col2 col3 col4 col5
[1,]    1   NA   NA   13   NA
[2,]   NA   NA   10   NA   18
[3,]   NA    7   NA   15   NA
[4,]    4   NA   NA   16   NA

Now I want to "collapse" this dataframe into a dataframe with less columns and with removed NA's. In fact I am looking for and "excel way of doing": removing one cell and the whole row will move one cell to the left.

The result in this example case would be:

     col1 col2 
[1,]    1   13   
[2,]   10   18   
[3,]    7   15   
[4,]    4   16   

has anyone an idea about how to do this in R? Many thanks in advance!

like image 766
rdatasculptor Avatar asked Apr 11 '14 09:04

rdatasculptor


People also ask

How do I combine multiple columns in R?

To concatenate two columns you can use the <code>paste()</code> function. For example, if you want to combine the two columns A and B in the dataframe df you can use the following code: <code>df['AB'] <- paste(df$A, df$B)</code>.

How do I remove multiple columns from a Dataframe in R?

We can delete multiple columns in the R dataframe by assigning null values through the list() function.


1 Answers

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
like image 120
Jonas Tundo Avatar answered Sep 24 '22 23:09

Jonas Tundo