R 在mutate中使用匿名函数
我想使用数据帧的一列中的字符串作为逐行搜索数据帧另一列中字符串的R 在mutate中使用匿名函数,r,R,我想使用数据帧的一列中的字符串作为逐行搜索数据帧另一列中字符串的sub搜索字符串。我想使用dplyr::mutate来实现这一点。我已经找到了一种使用匿名函数和apply实现的方法,但是我觉得apply应该不是必需的,我一定是在实现mutate的过程中出了问题。(是的,我知道tools::file\u path\u sans\u ext可以在不需要使用mutate的情况下给出最终结果;我只是想了解如何使用mutate) 以下是我认为应该有效但不可行的代码: files.vec <- dir
sub
搜索字符串。我想使用dplyr::mutate
来实现这一点。我已经找到了一种使用匿名函数和apply
实现的方法,但是我觉得apply
应该不是必需的,我一定是在实现mutate
的过程中出了问题。(是的,我知道tools::file\u path\u sans\u 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 = (function(x) {sub(paste0(".", x["extension"], "$"), "", x["file"])})(.)
)
编辑以回答评论
要在没有现有矢量化函数的情况下使用用户定义函数,可以使用Vectorize
如下所示:
string_fun <- Vectorize(function(x, y) {sub(paste0(".", x, "$"), "", y)})
files.split.df <- files.paths.df %>%
mutate(
no.ext = string_fun(extension, file))
string\u-fun显然你需要的是一大堆括号。看
在您的情况下,它看起来像:
files.split.df <- files.paths.df %>%
mutate(
no.ext = (function(x) {sub(paste0(".", x["extension"], "$"), "", x["file"])})(.)
)
编辑以回答评论
要在没有现有矢量化函数的情况下使用用户定义函数,可以使用Vectorize
如下所示:
string_fun <- Vectorize(function(x, y) {sub(paste0(".", x, "$"), "", y)})
files.split.df <- files.paths.df %>%
mutate(
no.ext = string_fun(extension, file))
string\u fun谢谢。我看到了那篇文章,但无法理解他们在做什么。我会仔细看看,然后接受你的答案。这个解决方案很有效。谢谢如果没有我想要使用的函数的预先存在的矢量化版本,我是否应该使用mapply
?谢谢。我看到了那篇文章,但无法理解他们在做什么。我会仔细看看,然后接受你的答案。这个解决方案很有效。谢谢如果没有我想要使用的函数的预先存在的矢量化版本,我应该使用mapply
?
files.split.df <- files.paths.df %>%
mutate(
no.ext = (Vectorize(function(x, y) {sub(paste0(".", x, "$"), "", y)}))(extension, file))