R中的数据帧操作-将单元格向左移动并删除NA [英] Dataframe manipulation in R - Shift cells to the left and remove NAs
本文介绍了R中的数据帧操作-将单元格向左移动并删除NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,其列由随机分布的值和NA组成,如下所示:
I have a dataframe whose columns consists of randomly distributed values and NAs, as seen below:
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移到左侧-看起来应该像这样
I want to remove all NAs and shift the non-NAs to the left - it should look like this
# [,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" "" ""
这篇关于R中的数据帧操作-将单元格向左移动并删除NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文