gpt4 book ai didi

r - 在 mutate 中使用匿名函数

转载 作者:行者123 更新时间:2023-12-02 17:01:40 25 4
gpt4 key购买 nike

我想使用数据框一列中的字符串作为逐行搜索数据框另一列中字符串的 sub 搜索字符串。我想使用 dplyr::mutate 来做到这一点。我想出了一种使用匿名函数和 apply 来做到这一点的方法,但我觉得 apply 不是必需的,我一定是做错了什么正在实现 mutate。 (是的,我知道 tools::file_path_sans_ext 可以在不需要使用 mutate 的情况下为我提供最终结果;我只是想了解如何使用 mutate。)

以下是我认为应该有效但无效的代码:

files.vec <- dir(
dir.target,
full.names = T,
recursive = T,
include.dirs = F,
no.. = T
)

library(tools)
files.paths.df <- as.data.frame(
cbind(
path = files.vec,
directory = dirname(files.vec),
file = basename(files.vec),
extension = file_ext(files.vec)
)
)

library(tidyr)
library(dplyr)
files.split.df <- files.paths.df %>%
mutate(
no.ext = function(x) {
sub(paste0(".", x["extension"], "$"), "", x["file"])
}
)
| Error in mutate_impl(.data, dots) :
| Column `no.ext` is of unsupported type function

下面是有效的代码,使用apply:

files.split.df <- files.paths.df %>% 
mutate(no.ext = apply(., 1, function(x) {
sub(paste0(".", x["extension"], "$"), "", x["file"])
}))

这可以在没有apply的情况下完成吗?

最佳答案

显然您需要的是一大堆括号。参见 https://stackoverflow.com/a/36906989/3277050

在你的情况下它看起来像:

files.split.df <- files.paths.df %>% 
mutate(
no.ext = (function(x) {sub(paste0(".", x["extension"], "$"), "", x["file"])})(.)
)

因此,如果将整个函数定义括在方括号中,您就可以将其视为常规函数并为其提供参数。

新答案

实际上,这根本不是使用 mutate 的正确方法。我首先关注匿名函数部分,而没有看你实际在做什么。您需要的是 sub 的矢量化版本。所以我使用了 stringr 包中的 str_replace 。然后你可以只按名称引用列,因为这就是 dplyr 的优点:

library(tidyr)
library(dplyr)
library(stringr)

files.split.df <- files.paths.df %>%
mutate(
no.ext = str_replace(file, paste0(".", extension, "$"), ""))

编辑回复评论

要在没有现有向量化函数的情况下使用用户定义的函数,您可以像这样使用 Vectorize:

string_fun <- Vectorize(function(x, y) {sub(paste0(".", x, "$"), "", y)})
files.split.df <- files.paths.df %>%
mutate(
no.ext = string_fun(extension, file))

或者如果你真的不想给函数命名,我不推荐这样做,因为它更难阅读:

files.split.df <- files.paths.df %>% 
mutate(
no.ext = (Vectorize(function(x, y) {sub(paste0(".", x, "$"), "", y)}))(extension, file))

关于r - 在 mutate 中使用匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53870293/

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