使用dplyr重新编码多列

编程入门 行业动态 更新时间:2024-10-28 15:18:57
本文介绍了使用dplyr重新编码多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个数据帧,在其中重新编码了几列,因此将999设置为NA

I had a dataframe where I recoded several columns so that 999 was set to NA

dfB <-dfA %>% mutate(adhere = if_else(adhere==999, as.numeric(NA), adhere)) %>% mutate(engage = if_else(engage==999, as.numeric(NA), engage)) %>% mutate(quality = if_else(quality==999, as.numeric(NA), quality)) %>% mutate(undrstnd = if_else(undrstnd==999, as.numeric(NA), undrstnd)) %>% mutate(sesspart = if_else(sesspart==999, as.numeric(NA), sesspart)) %>% mutate(attended = if_else(attended>=9, as.integer(NA), attended))

我想使用mutate_at()和一定范围的列和recode()代替if_else(),但是我对如何赋予它条件感到困惑.我认为基于某些mutate_all示例,类似999 = NA的东西-但我还需要NA来匹配.x的类型,但我不确定如何使它变得对类型敏感

I want to use mutate_at() and a range of columns and recode() instead of if_else(), but I am stuck on how to give it the condition. I think something like 999 = NA based on some mutate_all examples -- but I also need the NA to match the type of .x and I am unsure how to get it to be type sensitive

我尝试过:

y <- data.frame(y1=c(1,2,999,3,4), y2=c(1L, 2L, 999L, 3L, 4L), y3=c(T,T,F,F,T)) z <- y %>% mutate_at( vars(y1:y2), funs(recode(.,`999` = as.numeric(NA))))

但是我收到警告未替换为.x的NA的值不兼容.请详尽指定替换项或提供.default,并且我看到它用数字表示,而不是用整数y2表示"

But I get a warning "Unreplaced values treated as NA as .x is not compatible. Please specify replacements exhaustively or supply .default " and I can see that it worded for the numeric column, but not for the integer column y2"

> z y1 y2 y3 1 1 NA TRUE 2 2 NA TRUE 3 NA NA FALSE 4 3 NA FALSE 5 4 NA TRUE

推荐答案

我在准确了解您要完成的工作时遇到了麻烦,所以请告诉我是否还不够.

I'm having trouble understanding exactly what you want to accomplish, so let me know if this isn't quite it.

library(dplyr) y <- data.frame(y1=c(1,2,999,3,4), y2=c(1L, 2L, 999L, 3L, 4L), y3=c(T,T,F,F,T)) y #> y1 y2 y3 #> 1 1 1 TRUE #> 2 2 2 TRUE #> 3 999 999 FALSE #> 4 3 3 FALSE #> 5 4 4 TRUE z <- y %>% mutate_at(vars(y1:y2), ~ifelse(. == 999, NA, .)) z #> y1 y2 y3 #> 1 1 1 TRUE #> 2 2 2 TRUE #> 3 NA NA FALSE #> 4 3 3 FALSE #> 5 4 4 TRUE

更多推荐

使用dplyr重新编码多列

本文发布于:2023-10-23 19:30:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521803.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:dplyr

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!