使用mutate_at使用列名称更新单元格值 [英] Update cell values with the column name using mutate_at

查看:409
本文介绍了使用mutate_at使用列名称更新单元格值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理调查数据.一些问题要求参与者检查适用于他们的所有选项.在我当前拥有的数据框中,对于每个可能的响应都有一列,如果参与者选择了该选项,则记录为1的值.例如,对于您在工作中经历了以下哪些情感?"这个问题,选择了乏味",压力",知足",我的数据框将如下所示:

I am processing survey data. Some of the questions ask participants to check all of the options that apply to them. In the dataframe I currently have, there is a column for each of the possible responses, with a value of 1 recorded if the participant selected that option. For example, for the question "Which of the following emotions have you experienced at work?", with the options "Boredom", "Stress", "Contentment", my dataframe would look like this:

df <- data.frame(
  id = seq(1,3,1),
  boredom = c(NA, 1, NA),
  stress = c(1, 1, 1),
  contentment = c(NA, NA, NA)
)

我想用列名更新等于1的任何单元格值,以便有一个如下所示的数据框:

I want to update any cell values equal to 1 with the name of the column, so that I have a dataframe that looks like this:

df2 <- data.frame(
  id = seq(1,3,1),
  boredom = c(NA, 'boredom', NA),
  stress = rep('stress', 3), 
  contentment = rep(NA, 3)
)

然后,我可以使用dplyr :: unite创建一列,将一列参与者报告的所有情绪存储在该列中.

I can then use dplyr::unite to create a column that stores all the emotions that participants report experiencing in one column.

我的直观方法是使用mutate_at和ifelse(),但是我不知道如何在对ifelse()的调用中引用列的名称.例如,我想写这样的东西:

My intuitive approach is to use mutate_at and ifelse(), but I don't know how to reference the name of the column in the call to ifelse(). For example, I want to write something like this:

df_updated <- df %>% 
  mutate_at(vars(boredom:stress), funs(ifelse(. == 1, 'relevant column name', .)))

我希望有人可以告诉我如何在ifelse()调用中访问列名.或者,如果我吠叫错误的树,也非常欢迎使用其他方法.

I am hoping someone can tell me how to access the column name in the ifelse() call. Or, if I'm barking up the wrong tree, guidance on another approach is also very welcome.

推荐答案

尝试一下:

df %>% mutate_at(vars(boredom:stress), funs(ifelse(. == 1, deparse(substitute(.)), .)))

这篇关于使用mutate_at使用列名称更新单元格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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