简体   繁体   English

读取R中的数据帧时出现问题

[英]Issue in reading data frames in R

I would like to plot my data set based on the changes over years. 我想根据多年来的变化绘制我的数据集。 My code 我的代码

df <- read.table(text = 'Year   impact
2017    1
2016    0.065037954
2016    0.102155159
2015    0.030964478
2015    0.100059625
2015    0.089210196
2014    0.034352628
2014    0.080435423
2012    0.054331258
2011    0.052896022
2011    0.087341494
2010    0.025212239
2010    0.0456487
',header=TRUE)

ggplot(data=df, aes(x=Year)) +
  geom_density() +
  ggtitle("Test")+
  xlab("Year")+
  ylab("Probability")

the x-axis should show years (2017 2016 ...) and the y-axis should show the values (minimum 0 and maximum 1). x轴应显示年份(2017 2016 ...),y轴应显示值(最小值0和最大值1)。 Is there any mistake in my code? 我的代码中有错误吗?

EDIT the out put dput(df) as follow: 编辑输出dput(df)如下:

structure(list(Yearimpact = c(20171, 20160.065037954, 20160.102155159, 
20160.030964478, 20160.100059625, 20160.089210196, 20160.034352628, 
20160.080435423, 20160.054331258, 20160.052896022, 20160.087341494, 
20160.025212239, 20160.0456487)), .Names = "Yearimpact", class = "data.frame", row.names = c(NA, 
-13L))

Using fread() from the data.table package is simpler, reads large datasets faster, and typically results in fewer errors. 使用data.table包中的fread()更简单,可以更快地读取大型数据集,并且通常可以减少错误。 Try this instead: 试试这个:

require(data.table)
require(ggplot2)

df <- fread("Year   impact
             2017    1
             2016    0.065037954
             2016    0.102155159
             2015    0.030964478
             2015    0.100059625
             2015    0.089210196
             2014    0.034352628
             2014    0.080435423
             2012    0.054331258
             2011    0.052896022
             2011    0.087341494
             2010    0.025212239
             2010    0.0456487")

If you need to convert this data table to a data frame for some reason afterword, you can use this: 如果由于某种原因需要将此数据表转换为数据帧,则可以使用以下命令:

df <- data.frame(df)

Either way, you can then graph the data: 无论哪种方式,您都可以绘制数据图:

ggplot(data=df, aes(x=Year)) +
  geom_density() +
  ggtitle("Test")+
  xlab("Year")+
  ylab("Probability")

Output: 输出:

在此输入图像描述

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

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