【问题标题】:R Linear Regression - Trouble setting valuesR 线性回归 - 设置值有问题
【发布时间】:2017-08-09 23:05:50
【问题描述】:

我是 R 新手,我需要帮助从我的数据集中获取一些值。该信息是城市列表中每年的美元金额。我正在尝试设置我的值,以便我可以对整个数据集名称估计值运行线性回归模型。

estimate <- read.csv("estimate.csv", check.names = FALSE) #Import
estimate

location  2010  2011  2012  2013  2014
city1     200   250   300   500   600
city2     300   300   400   650   780
city3     500   600   700   800   900

我只对 city3 的年展数据感兴趣。

我知道我可以使用代码 years &lt;- c(2010,2011,2012,2013,2014) 来创建我的年份变量,但我知道这仅适用于小表。

对于我的线性模型,我想首先 plot(years, values) 其中年份是 2:6 列,对应的值仅来自第 3 行。当我运行values &lt;- estimate[3, c(3,2:6] 时,我得到了值的数据,但是当我尝试为years &lt;- estimate[0, c(0,2:6)] 做同样的事情时,我得到一个包含 5 个变量的 0 对象。试图情节给我

Error in plot.window(...) : need finite 'xlim' values In addition: Warning messages: 1: In min(x) : no non-missing arguments to min; returning Inf 2: In max(x) : no non-missing arguments to max; returning -Inf 3: In min(x) : no non-missing arguments to min; returning Inf 4: In max(x) : no non-missing arguments to max; returning -In

理想情况下,我希望数据设置在:

years        values
2010         500
2011         600
2012         700
2013         800
2014         900

然后我可以运行 lm 函数。提前谢谢。我对 R 和 Stack 中的这些东西真的很陌生,所以请原谅我的新手。

【问题讨论】:

  • reshape::melt(estimate) ,然后是子集

标签: r linear-regression


【解决方案1】:

1) 提取 假设最后的注释中显示的数据可重现,我们可以像这样执行回归:

year <- as.numeric(names(estimate)[-1])
city3 <- unlist((estimate[3, -1]))
lm(city3 ~ year)

2) 融化 或者我们可以将estimate 转换为长格式,这里是 15x3,然后修复名称并使年份数字化,然后执行回归:

library(reshape2)

long <- melt(estimate, id = "Location")
names(long) <- c("Location", "Year", "Estimate")
long$Year <- as.numeric(as.character(long$Year))

lm(Estimate ~ Year, long, subset = Location == "city3")

2a) reshape 也可以在没有任何这样的包的情况下完成从宽格式到长格式的转换:

yrs <- names(estimate)[-1]
long <- reshape(estimate, dir = "long", idvar = "Location", 
  varying = list(yrs), times = as.numeric(yrs), timevar = "Year", v.names = "Estimate")

lm(Estimate ~ Year, long, subset = Location == "city3")

注意:

Lines <- "
Location,2010,2011,2012,2013,2014
city1,200,250,300,500,600
city2,300,300,400,650,780
city3,500,600,700,800,900"
estimate <- read.csv(text = Lines, check.names = FALSE)

【讨论】:

    【解决方案2】:

    当您使用read.csv 读取 csv 文件时,第一行将成为数据框中的名称。试试

    names = colnames(estimate)
    

    您会看到names 是一个字符向量c("location", "2010", "2011", ...)。您可以通过删除第一项并将其转换为数字来将其转换为 years

    years = as.numeric(names[-1])
    

    【讨论】:

      猜你喜欢
      • 2012-07-24
      • 2018-11-17
      • 2018-12-14
      • 1970-01-01
      • 2013-02-11
      • 2020-09-19
      • 2018-01-08
      • 2022-12-29
      • 2012-12-07
      相关资源
      最近更新 更多