当前位置 : 主页 > 手机开发 > 无线 >

R中的数据帧操作 – 向左移动单元格并删除NA

来源:互联网 收集:自由互联 发布时间:2021-06-10
我有一个数据框,其列由随机分布的值和NA组成,如下所示: a-c("S","E","NA","S","NA")b-c("A","NA","M","G","K")c-c("I","NA","NA","NA","L")meh-dataframe(a,b,c)# [,1] [,2] [,3] [,4] [,5]#a "S" "E" "NA" "S" "NA"#b "A" "NA" "M"
我有一个数据框,其列由随机分布的值和NA组成,如下所示:

a<-c("S","E","NA","S","NA")
b<-c("A","NA","M","G","K")
c<-c("I","NA","NA","NA","L")
meh<-dataframe(a,b,c)

#  [,1] [,2] [,3] [,4] [,5]
#a "S"  "E"  "NA" "S"  "NA"
#b "A"  "NA" "M"  "G"  "K" 
#c "I"  "NA" "NA" "NA" "L"

我想删除所有的NA并将非NA移到左边 – 它应该是这样的

#  [,1] [,2] [,3] [,4]
#a "S"  "E"  "S"  
#b "A"  "M"  "G"  "K" 
#c "I"  "L"

有任何想法吗?

我们也可以使用stri_list2matrix

library(stringi)
stri_list2matrix(lapply(meh, function(x) x[x!='NA']), fill='', byrow=TRUE)
#    [,1] [,2] [,3] [,4]
#[1,] "S"  "E"  "S"  ""  
#[2,] "A"  "M"  "G"  "K" 
#[3,] "I"  "L"  ""   ""
网友评论