R 删除具有零行的数据帧

R 删除具有零行的数据帧,r,dataframe,R,Dataframe,我有超过57个数据帧,其中一些有零行。我如何移除这些 我试过下面的代码 test=ls() rm(dim(test[1]==0)) 我犯了一个错误 Error in rm(dim(test[1] == 0)) : ... must contain names or character strings 您应该提供一些要使用的数据集,但没有数据集,以下是一个示例: 编造一些数据 a <- data.frame() b <- data.frame(1:4, 5:8) 因

我有超过57个数据帧,其中一些有零行。我如何移除这些

我试过下面的代码

test=ls()    
rm(dim(test[1]==0))
我犯了一个错误

Error in rm(dim(test[1] == 0)) : 
  ... must contain names or character strings

您应该提供一些要使用的数据集,但没有数据集,以下是一个示例:

编造一些数据

a <- data.frame()
b <- data.frame(1:4, 5:8)
因此,您可以测试nrow=0的时间。您需要将test中存储的字符转换为实际变量

rm(dim(eval(parse(text = test[1])))[1] == 0)
上述工作通过使用

eval(parse(text = test[1]))
它将字符作为变量名进行计算

您可以选中test[1]来测试[i],或者编写apply函数来检查测试字符。

您需要使用
rm(list=)
来避免此错误

此代码应适用于:

test=ls()
rm(list=test[sapply(test,function(x) {
    d <- dim(get(x)); 
    length(d)==2 && sum(d)==0
    })])
使用以下方法可能更安全:

 rm(list=test[sapply(test,function(x) class(get(x))=="data.frame" && length(get(x))==0)])
在哪里

  • class()
    data.frame
  • length()
    为0

我们可以创建一个函数
isEmpty()
,该函数根据给定的“空”数据帧定义返回逻辑值。在这里,我假设列也为零,并将维度和设为零。但在此之前,我们可以通过确定
x
是否是数据帧来节省时间。然后,我们可以使用
eapply()
在环境上应用我们的函数。最后,只需收集名称并像往常一样删除即可

## create a function that returns a logical value
isEmpty <- function(x) {
    is.data.frame(x) && sum(dim(x)) == 0L
}
## apply it over the environment
empty <- unlist(eapply(.GlobalEnv, isEmpty))
## remove the empties
rm(list = names(empty)[empty])
注2:如果您只对具有零行的数据帧感兴趣,并且允许列,则在上述函数中将
sum(dim(x))==0L
更改为
nrow(x)==0L


注3:此答案假设所有57个数据帧都在全局环境中。如果它们在列表中(建议使用),则将
eapply()
更改为
lapply()
,并将
X
更改为您的列表。

该说Wooo了

这是解决办法


a
eapply
??这个巫术到底是什么?大家好,我已经尝试了下面所有的方法,我发现问题出在哪里了,问题出在哪里>a b test=ls()>test[1][1]“a”>test[2][1]“b”>dim(test[1])NULL>dim(test[2])NULL找不到dim(test[2])是不是有人想得到这个dim@PraveenRKaruppannan-通过该调用,您实际上要求的是
dim(“a”)
,该值为空,因为字符向量没有维度。您必须执行
dim(get(test[1]))
我尝试使用get()来获取数据,但是如果我将它放在rm()中,我会得到任何错误,如果rm(get(test[1])==0)){rm(get(test[1])}中的错误(get(test[1]):。。。若语句正确运行但rm()不正确,则必须包含名称或字符串
dim( data.frame(a=c(1), b=c(2))[0] )
[1] 1 0
 rm(list=test[sapply(test,function(x) class(get(x))=="data.frame" && length(get(x))==0)])
## create a function that returns a logical value
isEmpty <- function(x) {
    is.data.frame(x) && sum(dim(x)) == 0L
}
## apply it over the environment
empty <- unlist(eapply(.GlobalEnv, isEmpty))
## remove the empties
rm(list = names(empty)[empty])
isEmpty <- function(x) identical(x, data.frame())