簡體   English   中英

對lapply使用嵌套函數

[英]Using nested function with lapply

此代碼有效(耗時數小時和數秒,僅轉換為秒):

library(lubridate)
library(tidyverse)


original_date_time<-"2018-01-3111:59:59"
period_to_seconds(hms(paste(hour(original_date_time), minute(original_date_time),second(original_date_time), sep = ":")))

我有這個小標題:

  df<-data.frame("id"=c(1,2,3,4,5), "Time"=c("1999-12-31 10:10:10","1999-12-31 09:05:13","1999-12-31 00:05:25","1999-12-31 07:04","1999-12-31 03:05:07"))
    tib<-as_tibble(df)
    tib

結果:

# A tibble: 5 x 2
     id Time               
  <dbl> <fct>              
1     1 1999-12-31 10:10:10
2     2 1999-12-31 09:05:13
3     3 1999-12-31 00:05:25
4     4 1999-12-31 07:04   
5     5 1999-12-31 03:05:07

現在,我想將更改時間的代碼應用於tib$Time每個單元格。 我嘗試過:

time_converted_data_<-lapply(tib$Time, period_to_seconds(hms(paste(hour(tib$Time), minute(tib$Time),second(tib$Time), sep = ":"))))

但這給了我錯誤:

Error in match.fun(FUN) : 
  c("'period_to_seconds(hms(paste(hour(tib$Time), minute(tib$Time), ' is not a function, character or symbol", "'    second(tib$Time), sep = \":\")))' is not a function, character or symbol")

如何解決? 我想要R基本版本和tidyverse版本。

基數R

您的功能已向量化。 所以,你可以做

period_to_seconds(hms(paste(hour(tib$Time), minute(tib$Time),second(tib$Time), sep = ":")))
#[1] 36600 32700   300 25440 11100

對於非矢量化函數,您可以嘗試類似

foo = function(x){
    period_to_seconds(hms(paste(hour(x), minute(x),second(x), sep = ":")))
}
lapply(tib$Time, foo)
#[[1]]
#[1] 36610

#[[2]]
#[1] 32713

#[[3]]
#[1] 325

#[[4]]
#[1] 25440

#[[5]]
#[1] 11107

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM