通过删除R中的NA合并超过2列 [英] Combining more than 2 columns by removing NA's in R

查看:73
本文介绍了通过删除R中的NA合并超过2列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

乍一看,这似乎是在不使用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.

我的数据框如下:

     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

现在,我想将此数据帧折叠"为具有较少列和已删除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   

有人知道如何在R中执行此操作吗?提前非常感谢!

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

推荐答案

您可以为此使用apply.如果df是您的数据帧`:

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)]

输出:

#      col1 col2
#         1   13
#        10   18
#         7   15
#         4   16

这篇关于通过删除R中的NA合并超过2列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆