【问题标题】:sub setting a column between 2 dates子设置2个日期之间的列
【发布时间】:2019-01-02 03:13:18
【问题描述】:

我有一个名为 nestle 的数据框,我必须找到在两个指定日期(例如 01-01-2010 和 01-01-2015)之间具有列标题量的销售量。日期是作为因素给出的,我使用as.Date 语法将它们转换为日期。我试图使用子集-

 vol1 <- nestle(nestle$Volume >= "01-01-2010" & nestle$Volume <= "01-01-2015")

它给出一个错误,说

找不到函数“雀巢”

我是 R 新手,正在努力学习。

我的问题的第二部分是如果我想在 R 中设置两个列,即第一列和第六列,我应该怎么做?

如果它们是连续的,即从 3 到 6,我知道该怎么做。我尝试了相同的方法,但显示错误。

提前致谢。

【问题讨论】:

  • 需要使用括号[],如nestle[nestle$Volume &gt;= "01-01-2010" &amp; nestle$Volume &lt;= "01-01-2015"]
  • 这也可以:vol1 &lt;- subset(nestle, Volume &gt;= "01-01-2010" &amp; Volume &lt;= "01-01-2015")
  • 对不起,我完全忘记使用 [ ]。但是现在代码运行成功,但输出为空白。它显示了 1843 个条目,但没有列或行我仍然不知道为什么?
  • 请分享` dput(head(nestle)) `和你在问题的第二部分使用的代码。
  • 我给定的数据框名称是 NESTLEIND.NS,我将它分配给 Nestle Nestle 这个代码给出了 27000 nestle02 这个再次发出满桌。

标签: r date subset


【解决方案1】:

我有点怀疑Volume 列是否包含日期,通常应该将其称为“sales_date”。

对于日期/时间操作lubridate库非常方便

# Simulation of data.frame w/10000 rows
set.seed(123)
library(lubridate)
NESTLEIND.NS <- data.frame(sales_date = as_date(sample(10000, replace = TRUE) + 10000), 
                           matrix((1:10000) * 5, ncol = 5), 
                           Volume = 10 * abs(rnorm(10000)))


nestle <- NESTLEIND.NS

# Date subsetting
nestle_date <- nestle[nestle$sales_date >= dmy("01-01-2010") & 
  nestle$sales_date <= dmy("01-01-2015"), ]

# check result
str(nestle_date)

# Column subsetting
nestle_column <- nestle[, c(1, 6)]

# Check result
str(nestle_column)

【讨论】:

    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多