Using nested function with lapply

怎甘沉沦 提交于 2019-12-04 02:18:04

问题


This code works (takes hours minutes and seconds and converts to seconds only):

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 = ":")))

I have this tibble:

  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

result:

# 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

Now I want to apply that code that changes time above to every cell of tib$Time. I tried like:

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

But it gives me the error:

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")

How to fix that? I want both, R basic and tidyverse versions.


回答1:


Base R

Your function is vectorized. So, you could just do

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

For non vectorized functions, you could try something like

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


来源:https://stackoverflow.com/questions/57098929/using-nested-function-with-lapply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!