在R dplyr中进行更改/转换(通过自定义功能) [英] mutate/transform in R dplyr (Pass custom function)
问题描述
我正在使用新软件包dplyr并遇到一些困难。
I am using the new package , dplyr and facing some difficulties.
mutate(df,isOdd=digit%%2) or transform(df,isOdd=digit%%2)
两者都可以正常工作。
我在询问传递自定义方法的问题。
I am asking a question on passing custom method.
IsItOdd <- function(x) {
if(x%%2==0)
result<-"even"
else
result<-"odd"
return(result)
}
transform(df,isOdd=IsItOdd(digit))
这不起作用,因为所有数字的整个列都传递给该函数。
是否可以通过仅将一个单元格而不是整个列传递给函数来实现此目的?
This doesnt work because the whole column of all the digit is passed to the function. Is there a way to make this work by just passing that one cell to the function instead of the whole column ?
推荐答案
使用transform,您的函数必须在矢量上进行操作。您可以使用 ifelse
代替,它适用于矢量:
With transform your function has to operate on the vector. You can use ifelse
instead, which works on vectors:
isOdd <- function(x){ ifelse(x %% 2 == 0, "even", "odd") }
或者您可以使用 apply
函数之一将函数应用于列中的每个值:
Alternatively you can apply the function to every value in the column with one of the apply
functions:
isOdd <- function(x){
sapply(x, function(x){
if(x %% 2 == 0){
return("even")
}else{
return("odd")
}
})}
这篇关于在R dplyr中进行更改/转换(通过自定义功能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!