【问题标题】:ifelse calc displays correctly in console but not in data frame in Rifelse calc 在控制台中正确显示,但在 R 中的数据框中显示不正确
【发布时间】:2020-05-07 22:04:01
【问题描述】:

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

【问题讨论】:

    标签: r dataframe if-statement


    【解决方案1】:

    我们可以把ifelse里面的&lt;-去掉,放到外面

    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"    
    

    【讨论】:

    • 行得通!但我仍然不确定原始代码有什么问题。特别是如果我想传递第二个值(如果为真)。假设我还想获取之前的 ID 并在 ifelse 语句中添加:x$prev_ID
    • @seansteele witihiin ifelse, &lt;- 不推荐
    • 谢谢。如何根据一个 if 语句执行多次计算?
    • @seansteele 从 cmets 不清楚。能否请您发布一个新问题
    猜你喜欢
    • 2016-03-07
    • 2021-09-27
    • 2018-11-01
    • 2018-10-02
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多