简体   繁体   English

R 中的因子函数返回 NA

[英]Factor function in R returning NAs

I have a data frame with a column of 'months' and coordinating values.我有一个包含“月”列和协调值的数据框。 When I create a graph, the months are ordered alphabetically.创建图表时,月份按字母顺序排列。 I want to order the months using the factor function, but now my graph is only showing the month of May and 'NAs'.我想使用 factor 函数对月份进行排序,但现在我的图表只显示了 5 月份和 'NAs'。

xnames<-c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
Data$Month<-factor(Data$Month, levels = xnames)
ggplot(DAtaTidy_MergeRWPeaks2, (aes(x=factor(Month, xnames), y=Volume)), na.rm=TRUE) + 
    geom_bar() 

I tried embedding the factor in the ggplot function but it produced the same result.我尝试将因子嵌入到 ggplot 函数中,但它产生了相同的结果。 When I delete 'May' from 'xnames', the graph just shows NAs.当我从“xnames”中删除“May”时,图表只显示 NA。

在此处输入图片说明

We can't see your data, but the behavior is indicative of Data$Month containing a value that is not included in your level term xnames .我们看不到您的数据,但该行为表明Data$Month包含未包含在您的级别术语xnames Is anything misspelled?有没有拼错? I would suggest you compare levels(as.factor(Data$Month)) and xnames - it will certainly show you the issue.我建议你比较levels(as.factor(Data$Month))xnames - 它肯定会告诉你这个问题。

Example dataset that shows the same problem you have:显示您遇到的相同问题的示例数据集:

yums <- c('soup', 'salad', 'bread')
nums <- c(10, 14, 5)
df1 <- data.frame(yums, nums)

yum.levels <- c('soup', 'salad', 'bread', 'pasta')
ggplot(df1, aes(x=factor(yums, yum.levels), y=nums)) + geom_col()

That gives you this:这给你这个:

在此处输入图片说明

...but if we mispell one of them (like capitalizing "Soup" in yums ), you get this: ...但是如果我们拼错其中一个(比如在yums “Soup” yums ),你会得到这个:

yums1 <- c('Soup', 'salad', 'bread')
nums <- c(10, 14, 5)
df2 <- data.frame(yums1, nums)

yum.levels <- c('soup', 'salad', 'bread', 'pasta')
ggplot(df2, aes(x=factor(yums1, yum.levels), y=nums)) + geom_col()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM