【问题标题】:Using nested function with lapply使用带有 lapply 的嵌套函数
【发布时间】:2019-11-27 15:35:46
【问题描述】:

此代码有效(需要几小时分秒,并且只转换为秒):

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 basic 和 tidyverse 两个版本。

【问题讨论】:

  • lapply(tib$Time, function(x) period_to_seconds(hms(paste(hour(x), minute(x), second(x), sep = ":"))))。对于每个tib$Time 应用function(x)

标签: r function functional-programming tidyverse


【解决方案1】:

基础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

【讨论】:

  • 函数period_to_seconds是向量化函数,不需要lapply。 foo(tib$Time) 会起作用。
  • 如何将结果作为原始 tibble 的更改列而不是列表接收?
  • 谢谢。两种变体都醒了:第一个。 time_converted_data&lt;-tib time_converted_data$Time&lt;-sapply(tib$Time, function(x) period_to_seconds(hms(paste(hour(x), minute(x), second(x), sep = ":")))) 和第二个time_converted_data&lt;-tib time_converted_data$Time&lt;-unlist(lapply(tib$Time, function(x) period_to_seconds(hms(paste(hour(x), minute(x), second(x), sep = ":")))))
  • @vasili111,请注意您的第四次没有定义“07:04”的秒数,这会导致 d.b. 值的差异。显示在他的回答中。重要的是您的所有输入都采用相同的格式。
猜你喜欢
  • 2020-07-01
  • 2015-04-26
  • 1970-01-01
  • 2019-07-19
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多