【问题标题】:In R, why do [<-.data.frame` and `$<-.data.frame` behave differently?在 R 中,为什么 [<-.data.frame` 和 `$<-.data.frame` 表现不同?
【发布时间】:2017-07-06 04:57:47
【问题描述】:

在尝试将我的 data.frame 的一列从字符串转换为日期对象时,我收到了一个意外的结果以及一条相当可怕的警告消息:

my_dataframe <- data.frame(date = c("20070610", "20170611"))
my_dataframe["date"] <- strptime(my_dataframe$date, format = "%Y%m%d")

# Warning message:
# In `[<-.data.frame`(`*tmp*`, "date", value = list(sec = c(NA_real_,  :
#   provided 11 variables to replace 1 variables

my_dataframe

# my_dataframe
#   date
# 1    0
# 2    0

但是,如果我只是将 [&lt;-.data.frame 运算符替换为 $&lt;-.data.frame 运算符,我会收到我想要的结果,并且不会收到任何问题的警告:

my_dataframe <- data.frame(date = c("20070610", "20170611"))
my_dataframe$date <- strptime(my_dataframe$date, format = "%Y%m%d")
my_dataframe

# my_dataframe
#       date
# 1 20070610
# 2 20170611

我现在正在以完全不同的方式进行此分析,但我发现这种行为差异确实令人痛苦,如果有人能解释为什么会发生这种情况,我将不胜感激。

谢谢!

【问题讨论】:

  • my_dataframe_1 是什么?这是一个错字还是您正在处理不同的数据框?
  • 你学习过help("[")吗?
  • 我发现help("[.data.frame") 更有用。
  • 对于遇到类似问题的其他人,help("[.data.frame]") 中列出的关键细节是:For [ the replacement value can be a list: each element of the list is used to replace (part of) one column, recycling the list as necessary.

标签: r dataframe statistics


【解决方案1】:

[.data.frame$.data.frame 不同,因为[ 返回一个数据框(列表)而$ 返回一个向量。 $ 的括号等效为 [[,并且按预期工作。您还可以将分配的内容包装在 list() 中,以确保将其识别为单列。

my_dataframe <- data.frame(date = c("20070610", "20170611"))
my_dataframe["date2"] <- strptime(my_dataframe$date, format = "%Y%m%d")
my_dataframe[["date3"]] <- strptime(my_dataframe$date, format = "%Y%m%d")
my_dataframe$date4 <- strptime(my_dataframe$date, format = "%Y%m%d")
my_dataframe["date5"] <- list(strptime(my_dataframe$date, format = "%Y%m%d"))
my_dataframe
#       date date2      date3      date4      date5
# 1 20070610     0 2007-06-10 2007-06-10 2007-06-10
# 2 20170611     0 2017-06-11 2017-06-11 2017-06-11

# [[<-, $<-, and [<- list() all work fine

在这种情况下,我认为是 POSIX 类对象的额外属性使事情变得混乱。一般来说,当您知道只有一列时,最佳做法是使用[[

x = strptime(my_dataframe$date, format = "%Y%m%d")
attributes(x)
# $names
#  [1] "sec"    "min"    "hour"   "mday"   "mon"    "year"   "wday"   "yday"   "isdst"  "zone"  
# [11] "gmtoff"
# 
# $class
# [1] "POSIXlt" "POSIXt" 

【讨论】:

    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多