我有 n 个对象,我想将它们合并为一个 1 行 n 列的数据框。但是,某些对象可能是 NULL
或空字符串,我希望对象的名称成为数据框的名称。
如果我有
a <- 1
b <- 2
c <- 3
d <- NULL
e <- 'text'
f <- character(0)
我想做这样的事情:
mydf <- data.frame(a, b, c, d, e)
并在创建数据框时删除 NULL
值:
> mydf
a b c e
1 1 2 3 text
但是,如果我尝试使用 NULL
对象和空字符串,我会收到以下错误:
Error in data.frame(a, b, c, d, e) :
arguments imply differing number of rows: 1, 0
如果我编写某种函数来过滤掉 NULL
对象,我会丢失对象的名称并得到奇怪的列名称。
感谢您的帮助!
最佳答案
试试这个:
L <- list(a = a, b = b, c = c, d = d, e = e, f = f)
DF <- as.data.frame(matrix(L, 1, dimnames = list(NULL, names(L))))
DF
## a b c d e f
## 1 1 2 3 NULL text
str(DF)
## 'data.frame': 1 obs. of 6 variables:
## $ a:List of 1
## ..$ a: num 1
## $ b:List of 1
## ..$ b: num 2
## $ c:List of 1
## ..$ c: num 3
## $ d:List of 1
## ..$ d: NULL
## $ e:List of 1
## ..$ e: chr "text"
## $ f:List of 1
## ..$ f: chr
另请注意,矩阵 m
如下所示:
str(m)
## List of 6
## $ : num 1
## $ : num 2
## $ : num 3
## $ : NULL
## $ : chr "text"
## $ : chr(0)
## - attr(*, "dim")= int [1:2] 1 6
## - attr(*, "dimnames")=List of 2
## ..$ : NULL
## ..$ : chr [1:6] "a" "b" "c" "d" ...
关于r - 从 R 中具有某些 NULL 值的对象创建数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45023847/