R中的逻辑空值

时间:2018-11-27 14:38:20

标签: r

此表达式之后

good.rows<-ifelse(nchar(ufo$DateOccurred)!=10 | nchar(ufo$DateReported)!=10, 
FALSE, TRUE) 

我期望得到布尔的向量,但是我得到了

length(good.rows)

[1] 0

这是合乎逻辑的(空),正如我在R studio中看到的那样。我该怎么解决?

dput(head(ufo))

"structure(list(DateOccured = structure(c(9412, 9413, 9131, 9260, 
9292, 9428), class = "Date"), DateReported = structure(c(9412, 
9414, 9133, 9260, 9295, 9427), class = "Date"), Location = c(" Iowa City, IA", 
" Milwaukee, WI", " Shelton, WA", " Columbia, MO", " Seattle, WA", 
" Brunswick County, ND"), ShortDescription = c(NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_
), Duration = c(NA, "2 min.", NA, "2 min.", NA, "30 min."), LongDescription = c("Man repts. witnessing &quot;flash, followed by a classic UFO, w/ a tailfin at back.&quot; Red color on top half of tailfin. Became triangular.", 
"Man  on Hwy 43 SW of Milwaukee sees large, bright blue light streak by his car, descend, turn, cross road ahead, strobe. Bizarre!", 
"Telephoned Report:CA woman visiting daughter witness discs and triangular ships over Squaxin Island in Puget Sound. Dramatic.  Written report, with illustrations, submitted to NUFORC.", 
"Man repts. son&apos;s bizarre sighting of small humanoid creature in back yard.  Reptd. in Acteon Journal, St. Louis UFO newsletter.", 
"Anonymous caller repts. sighting 4 ufo&apos;s in NNE sky, 45 deg. above horizon.  (No other facts reptd.  No return tel. #.)", 
"Sheriff&apos;s office calls to rept. that deputy, 20 mi. SSE of Wilmington,  is looking at peculiar, bright white, strobing light."
)), row.names = c(NA, 6L), class = "data.frame")"

1 个答案:

答案 0 :(得分:1)

发生这种情况的原因有两个:

  • 您的数据集为空,请使用dim()方法进行检查。
  • 这些列不是字符类型,请使用class()进行检查 方法。
  • 如果两个都正确,请尝试运行nchar(...)语句

下面,我创建了一个可以正常工作的示例,在此过程中,我已经完成了上述步骤。将来,请提供一个可复制的示例作为问题的一部分。

# Create sample data
ufo <- data.frame(DateOccurred=c("a","bb","ccc"), 
                  DateReported=c("a","bb","ccc"), 
                  stringsAsFactors = FALSE)
print(ufo)

# Check size of data (make sure data has rows and columns are of type Character)
dim(ufo)
class(ufo$DateOccurred)
class(ufo$DateReported)

# Check nchar statements (Should run without error/warnings)
nchar(ufo$DateOccurred)
nchar(ufo$DateReported)

# Actual 
good.rows <- ifelse(nchar(ufo$DateOccurred)!=3 | nchar(ufo$DateReported)!=3,
                    FALSE, TRUE)
print(good.rows)
length(good.rows)