R dplyr mutate_at访问名称 [英] R dplyr mutate_at accessing colnames

查看:41
本文介绍了R dplyr mutate_at访问名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问由 dplyr :: mutate_at 处理的列名?

How could one access the column name being processed by dplyr::mutate_at?

比方说,我们希望将数据框的一列转换为具有存储在单独列表中的级别的因子.

Let's say we would like to convert a column of a data frame into factors with levels stored in a separate list.

df <- data.frame("C1"=c("A","B","C"), "C2"=c("D","E","F"))
df
  C1 C2
1  A  D
2  B  E
3  C  F

lst <- list("C2"=c("F","E","D"), "C3"=c("G","H","I"))
lst
$C2
[1] "F" "E" "D"

$C3
[1] "G" "H" "I"

以下所有触发错误或将所有列值替换为NA:

All of the following trigger error or replace all the column values by NA:

df %>%
mutate_at(vars(C2), function(x) factor(x, levels=lst$.))

df %>%
mutate_at(vars(C2), function(x) factor(x, levels=lst[[colnames(.)]]))

df %>%
mutate_at(vars(C2), function(x){col = as.name(.); factor(x, levels=lst$col))

推荐答案

之后,您可以在基本R中使用 Map 或从 purrr 中使用 map2 使用 intersect 来获取公共列.

You can use Map in base R or map2 from purrr after getting the common columns using intersect.

cols <- intersect(names(lst), names(df))
df[cols] <- Map(function(x, y) factor(x, levels = y), df[cols], lst[cols])

df[cols] <- purrr::map2(df[cols], lst[cols], ~factor(.x, levels = .y))

这篇关于R dplyr mutate_at访问名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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