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

How do I replace empty dataframe/data.tables from a list with a placeholder data.table?

此 post 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))

这个怎么样?由于你的placeholder很小,乘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

只是为了解释如何使用您的方法本身完成它!

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)

一个选项是使用 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