【问题标题】:Using fct_relevel over a list of variables using map_at在使用 map_at 的变量列表上使用 fct_relevel
【发布时间】:2017-01-25 18:56:49
【问题描述】:

我有一堆具有相同级别的因子变量,我希望使用 forcats 包中的 fct_relevel 对它们进行类似的重新排序。许多变量名称以相同的字符开头(“Q11A”到“Q11X”、“Q12A”到“Q12X”、“Q13A”到“Q13X”等)。我想使用dplyr 中的starts_with 函数来缩短任务。以下错误没有给我错误,但它也没有做任何事情。是不是我做错了什么?

library(dplyr)
library(purrr)
library(forcats)
library(tibble)

#Setting up dataframe
f1 <- factor(c("a", "b", "c", "d"))
f2 <- factor(c("a", "b", "c", "d"))
f3 <- factor(c("a", "b", "c", "d"))
f4 <- factor(c("a", "b", "c", "d"))
f5 <- factor(c("a", "b", "c", "d"))
df <- tibble(f1, f2, f3, f4, f5)

levels(df$f1)
[1] "a" "b" "c" "d"

#Attempting to move level "c" up before "a" and "b".
df <- map_at(df, starts_with("f"), fct_relevel, "c")

levels(df$f1)
[1] "a" "b" "c" "d" #Didn't work

#If I just re-level for one variable:
fct_relevel(df$f1, "c")
[1] a b c d
Levels: c a b d
#That worked.

【问题讨论】:

    标签: r dplyr purrr tidyverse


    【解决方案1】:

    我想你在找mutate_at

    df <- mutate_at(df, starts_with("f"), fct_relevel, ... = "c")
    
    df$f1
    
    [1] a b c d
    Levels: c a b d
    

    【讨论】:

    • 显然我对什么时候应该使用 purrr::map 以及什么时候应该使用 dplyr::mutate 感到困惑。
    • 这很容易被原谅。您通常希望对列使用不同的mutate 变体,并在mutate 中使用map 用于列表列和非向量化计算。
    • @akrun,对不起,我只找到了最终使用 mutate_each 的体面的骗子,计划弃用。如果你有一个好的mutate_at 目标,请随意锤击。
    • 没关系。你可能是对的,很难找到mutate_at的人
    猜你喜欢
    • 2021-05-23
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多