简体   繁体   English

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

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

This post How do I remove empty data frames from a list? 这篇文章如何删除列表中的空白数据框? talks about removing empty dataframes. 谈到删除空的数据框。 How do i remove empty dataframes(nrow =0) from a list and replace them with 1 row placeholder dataframes/data.tables? 如何从列表中删除空数据框(行= 0)并将其替换为1行占位符数据框/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)

I tried: 我试过了:

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

One option would be using lengths 一种选择是使用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

How about this? 这个怎么样? Since your placeholder is fairly small, it's not a problem to multiply it n times. 由于您的占位符很小,因此将其乘以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

Just to explain how you could complete it using your approach itself! 只是说明您如何使用自己的方法来完成它!

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM