首页 > 解决方案 > ifelse calc 在控制台中正确显示,但在 R 中的数据框中不正确显示

问题描述

当我运行以下代码时,它在控制台中正确显示,但数据框不正确,每一行都显示“IDK”

#sample data
x <- data.frame("ID" = 1:5, "action" = c("Assists","Goals", "Assists", "Goals", "Goals"), "team" ="FSU", "prev_action" = "text")

#code not working as expecting
ifelse( x$action == "Goals" & lag(x$action) == "Assists" & lag(x$team) == x$team,
        x$prev_action <- "Assists",x$prev_action <- "IDK")

运行代码后控制台显示:

[1] "IDK"     "Assists" "IDK"     "Assists" "IDK"   

...但是如果我运行这个...

print(x$prev_action)
[1] "IDK" "IDK" "IDK" "IDK" "IDK"

标签: rdataframeif-statement

解决方案


我们可以把<-里面的东西去掉,ifelse放在外面

x$prev_action <- ifelse( x$action == "Goals" & 
           lag(x$action) == "Assists" & lag(x$team) == x$team,
                        "Assists","IDK")
x$prev_action
#[1] "IDK"     "Assists" "IDK"     "Assists" "IDK"    

推荐阅读