在带有dplyr的R数据帧中使用用户定义的函数
可以在dplyr中使用用户定义的函数。但如果我使用以下代码:在带有dplyr的R数据帧中使用用户定义的函数,r,function,dplyr,paste,mutate,R,Function,Dplyr,Paste,Mutate,可以在dplyr中使用用户定义的函数。但如果我使用以下代码: create_string <- function(n) { new_string <- paste(c(0:n), collapse=';') return(new_string) } df <- data.frame(x = 1:3, number = c('4', '2', '1'), expected = c(create_string(4), create_string(2), create_stri
create_string <- function(n) {
new_string <- paste(c(0:n), collapse=';')
return(new_string)
}
df <- data.frame(x = 1:3, number = c('4', '2', '1'), expected = c(create_string(4), create_string(2), create_string(1)))
df %>% mutate(reality = create_string(number))
因此,您可以看到预期的输出不等于实际值(包括错误)问题是
mutate
一次填充所有行,这意味着不读取create\u string(4)
,您实际上得到的是create\u string(c(4,2,1))
。解决方案是以某种方式强制每次执行一个值
df%>%
变异(现实=sappy(数字,创建字符串))
#x数字预期现实
# 1 1 4 0;1.2.3.4 0;1.2.3.4.
# 2 2 2 0;1.2 0;1.2.
# 3 3 1 0;1 0;1.
备选方案:
df%>%
行()
变异(现实=创建字符串(数字))%>%
解组()
df%>%变异(reality=purrr::map\u chr(数字,创建字符串))
df%>%变异(现实=矢量化(创建字符串)(数字))
或者,您可以在内部对函数进行矢量化:
创建\u字符串
x number expected reality
1 1 4 0;1;2;3;4 0;1;2;3;4
2 2 2 0;1;2 0;1;2;3;4
3 3 1 0;1 0;1;2;3;4
Warning messages:
1: Problem with `mutate()` input `reality`.
i numerical expression has 3 elements: only the first used
i Input `reality` is `create_string(number)`.
2: In 0:n : numerical expression has 3 elements: only the first used