为什么 lubridate mdy() return 在 lapply() 中出错?

Why does lubridate mdy() return an error in lapply()?

我试图理解为什么我的 lubridate mdy() 函数在 lapply() 中返回错误以转换 dplyr 管道中的日期。我以类似的方法对其他数据使用了 mdy(),但还没有看到这个问题。我对 R 比较陌生,但直到现在才能够解决其他问题。我不是很熟悉如何使用 lapply().

我的数据是一个大型 .csv 水质数据,我对其进行子集化以简单地显示相关数据。

library(dplyr)
library(lubridate)
require(lubridate)

wq.all<-as.data.frame(read.csv('C:/WQdata.csv',header=TRUE,stringsAsFactors = FALSE))

test.wq<-wq.all[1:5,12:13]

class(test.wq)
[1] "data.frame"
mode(test.wq)
[1] "list"
str(test.wq)
'data.frame':   5 obs. of  2 variables:
 $ YearMonth : chr  "2019-07" "2019-06" "2019-05" "2019-04" ...
 $ SampleTime: chr  "07/09/2019 14:44" "06/10/2019 14:17" "05/22/2019 14:31" "04/08/2019 14:15" ...

str(test.wq) 中,SampleTime 是我试图从 chr 强制转换为 date 或至少 num 的相关数据。

首先,我不需要时间值,所以我使用 dplyr mutate() 创建了 SampleDate 只有 10 个字符的日期,然后试图强制使用 mdy():

wq.date<-test.wq%>%
  mutate(SampleDate=str_sub(test.wq[[2]],start=0,end=10))%>%
  mdy(SampleDate)

但是这个returns一个错误:

Error in lapply(list(...), .num_to_date) : object 'SampleDate' not found

如果我只使用 mutate() 它似乎一切正常,并为我提供了我正在寻找的新 SampleDate 列:

wq.date<-test.wq%>%
  mutate(SampleDate=str_sub(test.wq[[2]],start=0,end=10))

head(wq.date)

  YearMonth       SampleTime SampleDate
1   2019-07 07/09/2019 14:44 07/09/2019
2   2019-06 06/10/2019 14:17 06/10/2019
3   2019-05 05/22/2019 14:31 05/22/2019
4   2019-04 04/08/2019 14:15 04/08/2019
5   2019-03 03/13/2019 14:19 03/13/2019

str(wq.date)

'data.frame':   5 obs. of  3 variables:
 $ YearMonth : chr  "2019-07" "2019-06" "2019-05" "2019-04" ...
 $ SampleTime: chr  "07/09/2019 14:44" "06/10/2019 14:17" "05/22/2019 14:31" "04/08/2019 14:15" ...
 $ SampleDate: chr  "07/09/2019" "06/10/2019" "05/22/2019" "04/08/2019" ...

所以它似乎只会在我尝试使用 mdy() 强制时导致错误,即使 SampleDate 显然存在并且我相信我引用它是正确的。 我研究了其他帖子 here and ,但似乎都没有解决这个问题。

想法?非常感谢!

我们需要将它放在 mutate 中或提取列,否则,它将在整个 data.frame 上应用该函数。根据?mdy

Transforms dates stored in character and numeric vectors to Date or POSIXct objects

因此,如果输入不是 vector,它将不起作用

library(dplyr)
library(lubridate)
library(stringr)
test.wq%>%
   mutate(SampleDate=str_sub(SampleTime,start=0,end=10))%>%
   mutate(date = mdy(SampleDate))