将嵌套函数与lapply一起使用 [英] Using nested function with lapply
本文介绍了将嵌套函数与lapply一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码有效(耗时数分钟和几秒,仅转换为秒):
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 = ":")))
我有这个小标题:
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
的每个单元格.我尝试过:
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 = ":"))))
但是它给了我错误:
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版本.
How to fix that? I want both, R basic and tidyverse versions.
推荐答案
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
这篇关于将嵌套函数与lapply一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文