2017-08-03 45 views
1

以下链接我可以使用any()和next()来摆脱R中的空数据帧吗?

if else statement gone bad

建议不要使用

> any(c(5,6,7))==0 
[1] FALSE 

我一直在使用的任何()在摆脱空数据帧的()循环像这样的提法:

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 

当然,如果我不关闭警告,我得到这个:

Warning message: 
In any(temp$var1) : coercing argument of type 'double' to logical 

是否有我不应该用这种方式绕过空白数据帧的原因?什么会更好?

我实际上是在线试图找到一种方法来解决这个错误,当我发现建议我不应该使用任何()这种方式的链接。

+2

看看'any(rep(0,10))== FALSE' –

+1

如果评论不够清楚,小心你的括号! 'any(c(5,6,7))== 0'将首先计算任意(c(5,6,7))'。这有意义吗?在你的控制台输入'any(c(5,6,7))',想想它可能会告诉你什么。无论你得到什么结果,你用'== 0'比较'0'.....你的意思是'any(c(5,6,7)== 0)'。你在你的循环中重复这个错误。 – Gregor

回答

3

考虑创建dataframes的列表,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> (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 
相关问题