重新编码列中的观察以获取特定的ID [英] Recode observation in column for a specific ID

查看:67
本文介绍了重新编码列中的观察以获取特定的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为调查"的数据集.在此,我有单独的ID行,列中有很多问题.我需要将1列中的值重新编码为NA并将观察值移至另一列.

I have a dataset, called 'survey'. In this I have rows of individual IDs, and columns with many questions. I need to recode the value in 1 column as NA and move the observation to the other column.

例如:

ID    Fruit    Vegetable
aaa   NA       grape 
bbb   NA       tomato
ccc   apple    NA
ddd   peach    NA

我想更改属于ID aaa和bbb的葡萄和番茄观察值,以将其放入水果列​​(调查受访者将其放在错误的列中),然后将NA留在后面.

I want to change the grape and tomato observations, belonging to ID aaa and bbb to put them into the fruit column (survey respondents put them in the wrong column) and leave NA behind.

外观如下:

ID    Fruit    Vegetable
aaa   grape    NA 
bbb   tomato   NA
ccc   apple    NA
ddd   peach    NA

非常感谢您

推荐答案

基本上,我们将使用2个条件来完成此任务.第一个将检查是否为NA,并在您要重新编码的名称列表(fct2recode)中.如果它在fct2recode中,则第二个将从第二列中将其删除.

Basically, we'll use 2 conditionals to accomplish this. The first will check if it's NA and in your list of names to recode (fct2recode). The second will remove it from the second column if it was in fct2recode.

library(tidyverse)

df <- read_table("ID    Fruit    Vegetable
aaa   NA       grape 
bbb   NA       tomato
ccc   apple    NA
ddd   peach    NA")

fct2recode <- c("grape", "tomato")

df %>%
    mutate(Fruit = ifelse(is.na(Fruit) & Vegetable %in% fct2recode, 
                          Vegetable, Fruit),
           Vegetable = ifelse(Vegetable %in% fct2recode, NA, Vegetable))

这将导致:

# A tibble: 4 x 3
  ID    Fruit  Vegetable
  <chr> <chr>  <chr>    
1 aaa   grape  NA       
2 bbb   tomato NA       
3 ccc   apple  NA       
4 ddd   peach  NA   

我希望这种方法对于您的问题足够通用.

I hope this approach is generalizable enough for your problem.

对于ID为"aaa"的特定目标对象,和"bbb",您可以将它们作为条件添加到 ifelse :

To specific target obs with IDs "aaa" and "bbb", you can add them as condition in the ifelse:

df %>%
    mutate(Fruit = ifelse(ID %in% c("aaa", "bbb"), Vegetable, Fruit),
           Vegetable = ifelse(ID %in% c("aaa", "bbb", NA, Vegetable)))

这篇关于重新编码列中的观察以获取特定的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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