簡體   English   中英

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

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

這篇文章如何刪除列表中的空白數據框? 談到刪除空的數據框。 如何從列表中刪除空數據框(行= 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)

我試過了:

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

一種選擇是使用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

這個怎么樣? 由於您的占位符很小,因此將其乘以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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM