与in运算符%in%一起使用mutate_at [英] using mutate_at with the in operator %in%

查看:50
本文介绍了与in运算符%in%一起使用mutate_at的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些变量的数据框以反转代码.我有一个单独的向量,其中包含所有要反转代码的变量.我想使用mutate_at()或其他一些简洁的方法,以一行代码将它们全部反向编码.这是数据集和要反转的项的向量

I have a data frame with a few variables to reverse code. I have a separate vector that has all the variables to reverse code. I'd like to use mutate_at(), or some other tidy way, to reverse code them all in one line of code. Here's the dataset and the vector of items to reverse

library(tidyverse)
mock_data <- tibble(id = 1:5,
       item_1 = c(1, 5, 3, 5, 5),
       item_2 = c(4, 4, 4, 1, 1),
       item_3 = c(5, 5, 5, 5, 1))

reverse <- c("item_2", "item_3")

这就是我想要的样子,仅将项目2和3反向编码:

Here's what I want it to look like with only items 2 and 3 reverse coded:

library(tidyverse)

solution <- tibble(id = 1:5,
                   item_1 = c(1, 5, 3, 5, 5),
                   item_2 = c(2, 2, 2, 5, 5),
                   item_3 = c(1, 1, 1, 1, 5))

我已经在下面的代码中尝试过了.我知道该重新编码是正确的,因为我已将其用于其他数据集,但是我知道%in%运算符有些问题.

I've tried this below code. I know that the recode is correct because I've used it for other datasets, but I know something is off with the %in% operator.

library(tidyverse)
mock_data %>%
  mutate_at(vars(. %in% reverse), ~(recode(., "1=5; 2=4; 3=3; 4=2; 5=1")))

Error: `. %in% reverse` must evaluate to column positions or names, not a logical vector

任何帮助将不胜感激!

推荐答案

您可以直接将 reverse 赋予 mutate_at ,而无需 vars(.%in%反向).而且我会将反转简化为6减去当前值.

You can give reverse directly to mutate_at, no need for vars(. %in% reverse). And I would simplify the reversing as 6 minus the current value.

mock_data %>% mutate_at(reverse, ~6 - .)
# # A tibble: 5 x 4
#      id item_1 item_2 item_3
#   <int>  <dbl>  <dbl>  <dbl>
# 1     1      1      2      1
# 2     2      5      2      1
# 3     3      3      2      1
# 4     4      5      5      1
# 5     5      5      5      5

如果 reverse 可能包含不在 mock_data 中的列,而您想跳过这些列,请使用 mutate_at(vars(one_of(reverse)),...)

If there's a possibility that reverse includes columns that are not in mock_data, and you want to skip those, use mutate_at(vars(one_of(reverse)), ...)

这篇关于与in运算符%in%一起使用mutate_at的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆