[英]using mutate_at with the in operator %in%
我有一個帶有一些變量的數據框來反轉代碼。 我有一個單獨的向量,其中包含要反轉代碼的所有變量。 我想使用 mutate_at() 或其他一些整潔的方式,在一行代碼中對它們進行反向編碼。 這是數據集和要反轉的項目向量
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 項反向編碼:
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% 運算符有問題。
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
任何幫助,將不勝感激!
你可以直接給mutate_at
reverse
,不需要vars(. %in% reverse)
。 我會將反向簡化為 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
如果reverse
可能包含不在mock_data
列,並且您想跳過這些列,請使用mutate_at(vars(one_of(reverse)), ...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.