当我运行以下代码时,它在控制台中正确显示,但数据帧不正确,每行都显示"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"
我们可以移除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"