简体   繁体   English

将 mutate_at 与 in 运算符 %in% 一起使用

[英]using mutate_at with the in operator %in%

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.我想使用 mutate_at() 或其他一些整洁的方式,在一行代码中对它们进行反向编码。 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")

Here's what I want it to look like with only items 2 and 3 reverse coded:这是我希望它看起来像只有第 2 项和第 3 项反向编码:

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))

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.我知道重新编码是正确的,因为我已经将它用于其他数据集,但我知道 %in% 运算符有问题。

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

Any help would be appreciated!任何帮助,将不胜感激!

You can give reverse directly to mutate_at , no need for vars(. %in% reverse) .你可以直接给mutate_at reverse ,不需要vars(. %in% reverse) And I would simplify the reversing as 6 minus the current value.我会将反向简化为 6 减去当前值。

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

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)), ...)如果reverse可能包含不在mock_data列,并且您想跳过这些列,请使用mutate_at(vars(one_of(reverse)), ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM