将非 NA 单元格向左移动 [英] Shifting non-NA cells to the left
本文介绍了将非 NA 单元格向左移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据集中有很多 NA,我需要将所有这些单元格(在行级别)向左移动.
There are many NA's in my dataset and I need to shift all those cells (at row level) to the left.
示例 - 我的数据框:
Example- my dataframe:
df=data.frame(x=c("l","m",NA,NA,"p"),y=c(NA,"b","c",NA,NA),z=c("u",NA,"w","x","y"))
df
x y z
1 l <NA> u
2 m b <NA>
3 <NA> c w
4 <NA> <NA> x
5 p <NA> y
我想将上面的数据框转换成这样:
I want the above dataframe converted into this:
x y z
1 l u NA
2 m b NA
3 c w NA
4 x <NA> NA
5 p y NA
请帮忙.
谢谢.
推荐答案
你可以使用标准的apply
函数:
You can use the standard apply
function:
df=data.frame(x=c("l","m",NA,NA,"p"),y=c(NA,"b","c",NA,NA),z=c("u",NA,"w","x","y"))
df2 = as.data.frame(t(apply(df,1, function(x) { return(c(x[!is.na(x)],x[is.na(x)]) )} )))
colnames(df2) = colnames(df)
> df
x y z
1 l <NA> u
2 m b <NA>
3 <NA> c w
4 <NA> <NA> x
5 p <NA> y
> df2
x y z
1 l u <NA>
2 m b <NA>
3 c w <NA>
4 x <NA> <NA>
5 p y <NA>
这篇关于将非 NA 单元格向左移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文