【问题标题】:Determining the number of objects in a vector确定向量中的对象数量
【发布时间】:2019-02-26 15:45:47
【问题描述】:

我有一个带有重复值的字符数据向量。我的最终目标是创建一个条形图,显示向量中每个唯一值出现的频率。很长的路要走如下:

 object1=length(df$vector[df$vector=="object1"])
 object2=length(df$vector[df$vector=="object2"])
 object3=length(df$vector[df$vector=="object3"])
 amounts=c(object1,object2, object3)
 barplot(amounts)

这可行,但当有许多唯一值时会很麻烦,这表明可以使用循环。我知道我可以通过“unique()”命令获得原始向量中唯一值的向量,但我不确定从那里去哪里。以下帖子让我思考,但无法回答我的问题。

Counting the number of elements with the values of x in a vector

R for loop on character variables

【问题讨论】:

  • table(df$vector)
  • 你在找barplot(table(df$vector))
  • 简单回答,谢谢!

标签: r plot bar-chart


【解决方案1】:

你可以使用 ggplot。

安装:

install.packages('ggplot2')

加载库:

library(ggplot2)

绘制条形图:

ggplot(df,aes(x=as.factor(vector)))+geom_bar()

如果你的向量是数字的,as.factor() 函数可以帮助将它变成分类的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    相关资源
    最近更新 更多