Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在mutate中使用匿名函数_R - Fatal编程技术网

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))