我正在尝试使用ifelse创建函数,但始终收到错误消息。我想创建一个标志变量,如果两个变量都为{abs(1)
,则填充1,否则填充0
我可以通过输入2个特定的变量来运行代码,但是在将其转换为函数时遇到麻烦。任何帮助表示赞赏!
#this is the code I got to work
df <- df %>%
mutate(Flag=ifelse(PTO_1== abs(1) && PTO_2 == abs(1), 1, 0))
#now trying to turn it into a function
flag <- function(var1,var2) {
df <- df %>%
mutate(Flag=ifelse(var1== abs(1) && var2 == abs(1), 1, 0))
}
#trying out the function, and get an error message
flag(PTO_1,PTO_2)
我希望创建一个新的'flag'变量,但会收到一条错误消息:
找不到对象“ PTO_1”
答案 0 :(得分:2)
您将收到错误消息,因为错误消息暗示PTO_1
不是您环境中的变量。
df <- data.frame("PTO_1" = rpois(n = 5, lambda = 1),
"PTO_2" = rpois(n = 5, lambda = 1))
PTO_1 PTO_2
1 1 3
2 2 2
3 0 0
4 1 1
5 0 1
#define the function to take the variable vectors as inputs:
flag <- function(x,y) {
Flag <- as.numeric(x == 1 & y == 1)
return(Flag)
}
#use mutate to send those variables through the function
df %>% mutate(Flag = flag(PTO_1, PTO_2))
PTO_1 PTO_2 Flag
1 1 3 0
2 2 2 0
3 0 0 0
4 1 1 1
5 0 1 0