我可以使用any()和next()来摆脱R中的空数据框吗? [英] Can I use any() and next() to get rid of empty data frames in R?
问题描述
以下链接
建议不要使用表达式
> any(c(5,6,7))== 0
[1] FALSE
我一直在使用any()来清除for()循环中的空数据框,如下所示:
id< - c(1,2,3,4,5,6)
len< - c(11.25,11.75,12,12,12.5,13.25)
df< - data.frame(id ,len)
bin.brks < - c(10,11,12,13,14)
options(warn = -1)#将警告关闭
for(m in 1:(length(bin.brks)-1)){
#subset加权到每个bin;当m = 1时
temp <-df [(df $ len> bin.brks [m]& df $ len< = bin.brks [m + 1]),]
#处理空的临时数据帧;如果dframe为空,则为FALSE:
if(any(temp $ len)== FALSE)next
}
options(warn = 0)#restore default warnings
当然,如果我不关闭这些警告,我会得到这个:
$ p $
警告信息:
任何(temp $ var1):强制参数类型'double'到逻辑
有没有一个原因,我不应该这样绕过空的数据框?什么是更好的方法?
我其实是网上试图找到一种方法来解决这个错误,当我找到了链接,建议我不应该使用任何()方法。
解决方案考虑用 lapply创建一个数据框列表
使用 Filter()
过滤掉空的数据框元素:
dfList < - lapply(seq_along(bin.brks),function(m)
df [(df $ len> bin.brks [m]& df $ len< = bin.brks [m +1]),])
print(dfList)
#[[1]]
#[1] id len
#< 0 rows> (或0长度row.names)
#[[2]]
#id len
#1 1 11.25
#2 2 11.75
#3 3 12.00
#4 4 12.00
#[[3]]
#id len
#5 5 12.5
# [[4]]
#id len
#6 6 13.25
[[5]]
#[1] id len
#< ; 0行> (或0长度row.names)
dfList< - Filter(函数(i)nrow(i)> 0,dfList)
print(dfList)
#[[1]]
#id len
#1 1 11.25
#2 2 11.75
#3 3 12.00
#4 4 12.00
#[[2]]
#id len
#5 5 12.5
#[[3]]
#id len
#6 6 13.25
The following link
suggests not to use the formulation
> any( c(5,6,7) )==0
[1] FALSE
I have been using any() to get rid of empty data frames in for() loops like this:
id <- c(1,2,3,4,5,6)
len <- c(11.25,11.75,12,12,12.5,13.25)
df <- data.frame(id,len)
bin.brks <- c(10,11,12,13,14)
options(warn = -1) # to turn warnings off
for (m in 1: (length(bin.brks)-1)){
#subset weights into each bin; empty when m=1
temp <- df[(df$len > bin.brks[m] & df$len <= bin.brks[m+1]),]
# deal with empty temp data frame; if the dframe is empty, this is FALSE:
if (any(temp$len)==FALSE) next
}
options(warn = 0) # restore default warnings
Of course, if I don't turn the warnings off, I get this:
Warning message:
In any(temp$var1) : coercing argument of type 'double' to logical
Is there a reason I shouldn't be getting around empty data frames this way? What would be a better way?
I actually was online trying to find a way to get around the error when I found the link that suggested I shouldn't be using any() this way at all.
解决方案 Consider creating a list of dataframes with lapply
and use Filter()
to filter out empty dataframe elements:
dfList <- lapply(seq_along(bin.brks), function(m)
df[(df$len > bin.brks[m] & df$len <= bin.brks[m+1]),])
print(dfList)
# [[1]]
# [1] id len
# <0 rows> (or 0-length row.names)
# [[2]]
# id len
# 1 1 11.25
# 2 2 11.75
# 3 3 12.00
# 4 4 12.00
# [[3]]
# id len
# 5 5 12.5
# [[4]]
# id len
# 6 6 13.25
# [[5]]
# [1] id len
# <0 rows> (or 0-length row.names)
dfList <- Filter(function(i) nrow(i) > 0, dfList)
print(dfList)
# [[1]]
# id len
# 1 1 11.25
# 2 2 11.75
# 3 3 12.00
# 4 4 12.00
# [[2]]
# id len
# 5 5 12.5
# [[3]]
# id len
# 6 6 13.25
这篇关于我可以使用any()和next()来摆脱R中的空数据框吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!