我是R的新手,正在寻找一些我将使用ggplot2的情节。我有一个数据集,它的值从4到12,但也有大约200个值,简单地标记为<4。
我正试着把它们放到R上的直方图中,但我很难选择盒子的大小。理想情况下,我希望它有1-4,4-7,7-10,10-13的箱子
我一直在阅读关于这个问题的文档和其他人的问题,但我在斗争街上。我有一些用AutoHotkey编写自动化程序的经验,但对于编码来说就这些了。我还没能成功地使用中断功能来做我想做的事情
目前我不知道如何做到这一点,并简单地有一个直方图与箱子(单个数字),R已经确定。然而,我已经看到在R上生成的图,其中的存储箱是间隔的。
提前感谢!
发布于 2019-09-09 19:47:26
我认为您的value-column将是一个字符,因为它同时包含值和"< 4“条目。我建议使用dplyr重新编码您的数据,并使用一个新变量作为垃圾箱的度量,如下所示:
library(tidyverse) # loads ggplot2 and dplyr
# some sample data
x <- iris %>%
# Sample data with '< 4' entries in your value column
rename(val=Sepal.Length) %>%
select(val,Species) %>%
mutate(val=ifelse(val < 4,"< 4",val))
# val Species
# 1 5.1 setosa
# 2 4.9 setosa
# 3 4.7 setosa
# 4 4.6 setosa
# 5 5.0 setosa
# 6 5.4 setosa
# ...
# Recoding your data
x <- x %>%
mutate(indicator=val) %>% # new variable: indicator
mutate(indicator=ifelse(val == "< 4", "1-3",indicator)) %>%
mutate(indicator=ifelse(between(round(as.numeric(val),0),4,6), "4-6",indicator)) %>%
mutate(indicator=ifelse(between(round(as.numeric(val),0),7,9), "7-9",indicator)) %>%
mutate(indicator=ifelse(between(round(as.numeric(val),0),10,12), "10-12",indicator))
# Plotting
ggplot(x,aes(indicator)) +
geom_histogram(stat="count") # counting each case in the indicator variable请注意,当R从1:3,从4:6开始计数时,您可能必须调整您的存储箱。其他编程语言不包括最后一个数字,但R包含。通过重新编码,您将在您的图上获得正确的标签。

这是你想要的吗?
发布于 2019-09-09 19:46:22
您的问题可能是您有一个字符向量,因为<4不能是数值向量中的元素。您需要替换该值,然后将向量强制转换为数字。然后你可以做一个直方图。
x <- sample(c("<4", 5:12), 100, T) # create sample vector
x <- ifelse(x == "<4", "4", x) # replace
x <- as.numeric(x) # coerce
hist(x, breaks = c(0, 4, 7, 10, 13))对于将来的问题,请提供您的问题的reproducible example。
https://stackoverflow.com/questions/57852948
复制相似问题