R数据框转换为命名列表时如何省略“ NA”

问题描述

我有一个结构如下的数据框:

a b c
1 1 1
2 2 2
3 3
4

我想将其转换为如下所示的命名列表:

Name:   Value:
a       1,2,3,4
b       1,3
c       1,2

但是,我现在得到的是:

Name:   Value:
a       1,NA
c       1,NA,NA

如您所见,空格被NA填充,如果可能的话,我想避免这种情况。作为参考,我用来执行此转换的代码很简单:

myNamedList <- as.list(myDataframe)

如果无法阻止添加NA,是否有功能将其从结果命名列表中删除?非常感谢您的建议。

解决方法

如评论中所述,as.list的结果将是等长向量(数据帧的行数)的列表,但是您可以从列表中删除NA:

myNamedList <- as.list(myDataframe)
lapply(myNamedList,function(v){v[!is.na(v)]})
,

data.framelist,因此您可以将na.omitlapply一起使用

# create the data in the example
myDataframe <- data.frame(
  a = 1:4,b = c(1:3,NA_integer_),c = c(1:2,NA_integer_,NA_integer_))

# convert to list and remove the NAs
myNamedList <- lapply(myDataframe,na.omit)

# show the result
myNamedList
#R> List of 3
#R>  $ a: int [1:4] 1 2 3 4
#R>  $ b: num [1:3] 1 2 3
#R>   ..- attr(*,"na.action")= 'omit' int 4
#R>  $ c: int [1:2] 1 2
#R>   ..- attr(*,"na.action")= 'omit' int [1:2] 3 4

# you can remove attributes if you want as follows
lapply(myNamedList,c)
#R> List of 3
#R>  $ a: int [1:4] 1 2 3 4
#R>  $ b: num [1:3] 1 2 3
#R>  $ c: int [1:2] 1 2