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

编程入门 行业动态 更新时间:2024-10-26 23:26:20
本文介绍了使用循环用同一列中的特定行值替换列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我从一项调查中获得了数据,该调查列出了收件人的姓名以及他们是否选择了该州的特定县.调查结构为未选择的任何县输出关闭,并为选择的县输出输出.该州约有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)

更多推荐

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

本文发布于:2023-10-31 07:57:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545503.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!