繁体   English   中英

尝试从 R 中的 csv 文件创建直方图

[英]Trying to create a histogram from csv file in R

下面是 csv 文件的摘录。

在此处输入图像描述

我正在尝试从上面数据中的 excel 文件创建直方图。 到目前为止,这是我的代码:

>read.csv("C:\\Users\\Owner\\Documents\\R Assignment- Part 2- 414001862\\employees.csv")
>> hist(e)
Error in hist.default(e) : 'x' must be numeric

我经常收到一个错误,说 x 必须是数字。 我究竟做错了什么? 如何正确输入数据以创建直方图?

在您使用 plot 直方图之前,您应该专注于在 R 中加载数据并将其保存为 object。

首先,您确定您的文件确实是.csv?

我将类似于您的数据的内容复制到 excel 中,将其保存为 a.csv 并使用以下代码:

setwd("")
read.csv("sample.csv")

您将在setwd() function 中放置文件所在路径的位置,文件名将是“sample”。 我得到以下信息:

   Salary.thousand.of... Number.of.Employees
1                   0-10                  50
2                  11-20                  20
3                  21-30                  30
4                  31-40                  70
5                  41-50                  80
6                  51-60                  90
7                  61-70                 100
8                  71-80                 120
9                  81-90                  80
10                   91+                  10

也许您有一个 excel 文件 (.xlsx),在这种情况下,您应该使用readxl package:

library(readxl)
read_excel("sample.xlsx")

这给了我以下信息:

# A tibble: 10 x 2                                                                                              
   `Salary(thousand of $)` `Number of Employees`
   <chr>                                   <dbl>
 1 0-10                                       50
 2 44136                                      20
 3 21-30                                      30
 4 31-40                                      70
 5 41-50                                      80
 6 51-60                                      90
 7 61-70                                     100
 8 71-80                                     120
 9 81-90                                      80
10 91+                                        10

如果将 object 存储为 df,则可以使用ggplot2中的 ggplot2 创建条形图:

library(tidyverse) ## You can also use "library(ggplot2)" if you don't want to load the whole tidyvsere
df <- read_excel("sample.xlsx") ## Store your dataframe as "df"


df %>%
  ggplot(aes(x = `Salary(thousand of $)`, y = `Number of Employees`)) + ## Assign which column goes to the x and y-axes
  geom_bar(stat = "identity") + ## Specify Plot type and assign the "identity" to the stat argument
  labs(title = "My plot title", ## Assign labels to your plot
       subtitle = "My plot subtitle",
       x = "Salary (in Thousands of $)") +
  theme_classic() ## Change from the default theme

这将 output 如下:

在此处输入图像描述

暂无
暂无

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

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