如何使用占位符data.table替换列表中的空dataframe / data.tables?

时间:2016-11-06 07:22:34

标签: r data.table dplyr apply lapply

这篇文章How do I remove empty data frames from a list?讨论了删除空数据帧的问题。如何从列表中删除空数据帧(nrow = 0)并将其替换为1行占位符dataframes / data.tables?

M1 <- data.frame(matrix(1:4, nrow = 2, ncol = 2))
M2 <- data.frame(matrix(nrow = 0, ncol = 0))
M3 <- data.frame(matrix(9:12, nrow = 2, ncol = 2))
mlist <- list(M1, M2, M3)

placeholder  = data.table(a=1,b=1)

我试过了:

lapply(mlist, function(x) ifelse(nrow(fundslist[[x]]) == 0, placeholder, x))

3 个答案:

答案 0 :(得分:5)

一种选择是使用lengths

mlist[!lengths(mlist)] <- list(placeholder)
str(mlist)
#List of 3
# $ :'data.frame':       2 obs. of  2 variables:
#  ..$ X1: int [1:2] 1 2
#  ..$ X2: int [1:2] 3 4
# $ :Classes ‘data.table’ and 'data.frame':      1 obs. of  2 variables:
#  ..$ a: num 1
#  ..$ b: num 1
#  ..- attr(*, ".internal.selfref")=<externalptr> 
# $ :'data.frame':       2 obs. of  2 variables:
#  ..$ X1: int [1:2] 9 10
#  ..$ X2: int [1:2] 11 12

答案 1 :(得分:3)

这个怎么样?由于你的占位符相当小,所以将它乘以n次并不是一个问题。

library(data.table)

M1 <- data.frame(matrix(1:4, nrow = 2, ncol = 2))
M2 <- data.frame(matrix(nrow = 0, ncol = 0))
M3 <- data.frame(matrix(9:12, nrow = 2, ncol = 2))
mlist <- list(M1, M2, M3)

placeholder  = data.table(a=1,b=1)

num.rows <- unlist(lapply(mlist, nrow))
num.zeros <- length(num.rows[num.rows == 0])
replacement <- replicate(num.zeros, {placeholder}, simplify = FALSE)

mlist[num.rows == 0] <- replacement

str(mlist)

List of 3
 $ :'data.frame':   2 obs. of  2 variables:
  ..$ X1: int [1:2] 1 2
  ..$ X2: int [1:2] 3 4
 $ :Classes ‘data.table’ and 'data.frame':  1 obs. of  2 variables:
  ..$ a: num 1
  ..$ b: num 1
  ..- attr(*, ".internal.selfref")=<externalptr> 
 $ :'data.frame':   2 obs. of  2 variables:
  ..$ X1: int [1:2] 9 10
  ..$ X2: int [1:2] 11 12

答案 2 :(得分:1)

只是解释一下如何使用自己的方法来完成它!

M1 <- data.frame(matrix(1:4, nrow = 2, ncol = 2))
M2 <- data.frame(matrix(nrow = 0, ncol = 0))
M3 <- data.frame(matrix(9:12, nrow = 2, ncol = 2))
mlist <- list(M1, M2, M3)

placeholder  = data.frame(matrix(c(1,1), nrow=1))

abc <- function(x){
  if(sum(dim(x))==0)
    return(data.frame(placeholder))
  else
    return(x)
}

lapply(mlist, abc)