【发布时间】:2019-07-16 17:28:59
【问题描述】:
我有一个自定义布尔函数来检查一个字符串(我的实际函数比下面提供的要多,这只是作为说明性示例提供的)。
如果我将第一个版本与 dplyr::mutate() 一起使用,它只会应用于第一个值,然后将所有行设置为该答案。
我可以将函数包装在 purr::map() 中,但是在较大的数据集上这似乎很慢。它似乎也不是 mutate 正常工作的方式。
library(tidyverse)
valid_string <- function(string) {
# Check the length
if (stringr::str_length(string) != 10) {
return(FALSE)
}
return(TRUE)
}
# Create a tibble to test on
test_tib <- tibble::tibble(string = c("1504915593", "1504915594", "9999999999", "123"),
known_valid = c(TRUE, TRUE, TRUE, FALSE))
# Apply the function
test_tib <- dplyr::mutate(test_tib, check_valid = valid_string(string))
test_tib
valid_string2 <- function(string) {
purrr::map_lgl(string, function(string) {
# Check the length
if (stringr::str_length(string) != 10) {
return(FALSE)
}
return(TRUE)
})
}
# Apply the function
test_tib <- dplyr::mutate(test_tib, check_valid2 = valid_string2(string))
test_tib
【问题讨论】:
标签: r function dplyr tidyverse