使用循环用同一列中的特定行值替换列中的值

使用循环用同一列中的特定行值替换列中的值

本文介绍了使用循环用同一列中的特定行值替换列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一项调查中获得了数据,该调查列出了收件人的姓名以及他们是否选择了该州的特定县.调查结构为未选择的任何县输出关闭,并为选择的县输出输出.该州约有100个县,因此最终有很多列实际上对应于同一问题.我要执行的操作是在县名称上用on替换所有单元格,在空白处用off替换所有单元格.从那里,我基本上可以轻松地将许多列合并为一个列.下面,我重新创建了一个简单的示例数据集

I have data obtained from a survey that lists the recipient's name and whether or not they selected a specific county in the state. The survey structure outputs an off for any county not selected and an for the selected county. The state has about 100 counties so there end up being a lot of columns that really correspond to the same question. What I am looking to do is replace any cells with on with the county name and any cells with off with a blank. From there I can basically unite many columns into one without much difficulty. Below I have recreated a brief example data set

name <- c("Recipient", "AB", "BC", "DF", "EF", "WE")
Q1 <- c("County1", "Off", "On", "On", "Off", "Off")
Q2 <- c("County2", "On", "Off", "Off", "Off", "Off")
Q3 <- c("County3", "Off", "Off", "Off", "On", "On")
dt <- data.frame(name, Q1, Q2, Q3)
> dt
       name       Q1           Q2           Q3
1 Recipient  County1      County2      County3
2        AB      Off           On          Off
3        BC       On          Off          Off
4        DF       On          Off          Off
5        EF      Off          Off           On
6        WE      Off          Off           On

我正在寻找所需的

       name       Q1           Q2           Q3
1 Recipient  County1      County2      County3
1        AB               County2
2        BC County1
3        DF County1
4        EF                             County3
5        WE                             County3

我不确定如何执行此操作并指定将第一行用于填充单元格.

I am not sure how to go about this and designate that the first row be used to fill cells.

感谢您的帮助.

推荐答案

我们创建一个逻辑向量,并根据该逻辑向量分配第一行值

We create a logical vector and assign the first row values based on the logical vector

i1 <- dt[-1] == 'On'
dt[-1][i1] <- unlist(dt[1, -1])[col(dt[-1])][i1]
dt[-1][!i1] <- ""
dt
#       name       Q1       Q2       Q3
#1 Recipient
#2        AB          County 2
#3        BC County 1
#4        DF County 1
#5        EF                   County 3
#6        WE                   County 3


或使用 dplyr

library(dplyr)
dt %>%
  mutate_at(vars(starts_with('Q')), ~ case_when(. == 'On' ~first(.), TRUE ~ ''))

数据

dt <- data.frame(name, Q1, Q2, Q3, stringsAsFactors = FALSE)

这篇关于使用循环用同一列中的特定行值替换列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 18:09