我尝试了以下。为什么我仍然收到forcats
警告?
#1我执行
plotdata <- dplyr::filter(Marriage, FALSE) %>% count(officialTitle)
if (nrow(plotdata) > 0){
str <- paste("nrows > 0. Number of rows is ", nrow(plotdata))
print(str)
print(plotdata)
但我得到以下信息:
[1] "nrows > 0. Number of rows is 1"
# A tibble: 1 x 2
officialTitle n
<fct> <int>
1 NA 0
Warning message:
Factor `officialTitle` contains implicit NA, consider using `forcats::fct_explicit_na`
#2 我注意到警告并执行以下操作
plotdata <- dplyr::filter(Marriage, FALSE) %>% count(officialTitle)
plotdata$officialTitle <- fct_explicit_na(plotdata$officialTitle)
if (nrow(plotdata) > 0){
str <- paste("nrows > 0. Number of rows is ", nrow(plotdata))
print(str)
print(plotdata)
这是结果:
[1] "nrows > 0. Number of rows is 1"
# A tibble: 1 x 2
officialTitle n
<fct> <int>
1 (Missing) 0
Warning message:
Factor `officialTitle` contains implicit NA, consider using `forcats::fct_explicit_na`
#3那我想也许这与forcats
. 我删除forcats
语句并从 plotdata 中删除 na,即
plotdata <- dplyr::filter(Marriage, FALSE) %>% count(officialTitle)
plotdata <- na.omit(plotdata)
if (nrow(plotdata) > 0){
str <- paste("nrows > 0. Number of rows is ", nrow(plotdata))
print(str)
print(plotdata)
输出如下:
[1] "nrows < 0. Number of rows is 0"
# A tibble: 0 x 2
# ... with 2 variables: officialTitle <fct>, n <int>
Warning message:
Factor `officialTitle` contains implicit NA, consider using `forcats::fct_explicit_na`
完整代码:
# Load packages ----
library(shiny)
library(ggplot2)
library(dplyr)
library(scales)
library(treemapify)
library(forcats)
# Load data ----
data(Marriage, package="mosaicData")
plotdata <- dplyr::filter(Marriage, FALSE) %>% count(officialTitle)
#plotdata$officialTitle <- fct_explicit_na(plotdata$officialTitle)
plotdata <- na.omit(plotdata)
if (nrow(plotdata) > 0){
str <- paste("nrows > 0. Number of rows is ", nrow(plotdata))
print(str)
print(plotdata)
ggplot(plotdata,
aes(fill = officialTitle,
area = n,
label = officialTitle)) +
geom_treemap() +
geom_treemap_text(colour = "white",
place = "centre") +
labs(title = "Marriages by officiate") +
theme(legend.position = "none")
} else {
str <- paste("nrows < 0. Number of rows is ", nrow(plotdata))
print(str)
print(plotdata)
}