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.
For example:
ID Fruit Vegetable
aaa NA grape
bbb NA tomato
ccc apple NA
ddd peach 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.
To look like:
ID Fruit Vegetable
aaa grape NA
bbb tomato NA
ccc apple NA
ddd peach NA
Thank you very much
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))
Which results in:
# 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.
EDIT:
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)))