r - 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"
解决方案
我们可以把<-
里面的东西去掉,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"
推荐阅读
- java - HttpClientErrorException getResponseBodyAsString() 无法将字节解析为字符串
- r - 如何使用 R 中的 Leaflet 将 csv-data 绑定到 geojson
- ffmpeg - 我对过滤器图描述中的无效文件索引 1 有疑问
- xml - Java Xml文档如何获取节点内的属性
- php - 如何对 Laravel 的 Cache::remember 功能的所有代码执行路径进行单元测试?
- angular - Ionic 3如何在行和列中显示数组中的数据?
- mysql - 从派生表中选择别名给出错误答案
- jquery - Jquery对话框背景不透明
- python - Pandas 版本的 SQL CROSS APPLY
- html - -webkit-background-clip:在 mozilla 中过渡结束后,带有过渡的元素上的文本不起作用,但在 chrome 中完美运行