gpt4 book ai didi

r - 使用函数 mutate_at 没有按预期迭代函数

转载 作者:行者123 更新时间:2023-12-04 11:46:13 25 4
gpt4 key购买 nike

我有一个列,我希望将其转换为秒。转换函数有效,但是当我尝试使用 mutate_at 迭代多列时。它没有像我预期的那样工作。我不知道我在 mutate_at 语法中遗漏了什么。

我有这个:

catalog
# A tibble: 4 x 3
# file start end
# <chr> <chr> <chr>
#1 20190506_205959-20190506_210459 1:58 3:00
#2 20190506_210507-20190506_211007 0 0:32
#3 20190506_205959-20190506_210459_2 0 3:18
#4 20190506_220712-20190506_221210 0 5

transform_time_to_seconds <- function(x) {
x %>%
str_split(":", simplify = TRUE) %>%
as.numeric() %>%
{.[1] * 60 +
ifelse(is.na(.[2]), 0, .[2])}
}

我应用mutate_at:

catalog %>%
mutate_at(vars(start, end), transform_time_to_seconds)
# A tibble: 4 x 3
# file start end
# <chr> <dbl> <dbl>
#1 20190506_205959-20190506_210459 60 180
#2 20190506_210507-20190506_211007 60 180
#3 20190506_205959-20190506_210459_2 60 180
#4 20190506_220712-20190506_221210 60 180

但我期望的是:

catalog %>%
mutate(start = map_dbl(start, transform_time_to_seconds),
end = map_dbl(end, transform_time_to_seconds))
# A tibble: 4 x 3
# file start end
# <chr> <dbl> <dbl>
#1 20190506_205959-20190506_210459 118 180
#2 20190506_210507-20190506_211007 0 32
#3 20190506_205959-20190506_210459_2 0 198
#4 20190506_220712-20190506_221210 0 300

有什么建议吗?


目录数据:

structure(list(file = c("20190506_205959-20190506_210459", "20190506_210507-20190506_211007", 
"20190506_205959-20190506_210459_2", "20190506_220712-20190506_221210"
), start = c("1:58", "0", "0", "0"), end = c("3:00", "0:32",
"3:18", "5")), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -4L), spec = structure(list(cols = list(
file = structure(list(), class = c("collector_character",
"collector")), start = structure(list(), class = c("collector_character",
"collector")), end = structure(list(), class = c("collector_character",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))
``

最佳答案

您还可以向量化您的函数

transform_time_to_seconds <- Vectorize(transform_time_to_seconds)

关于r - 使用函数 mutate_at 没有按预期迭代函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56024509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com