0
votes

Having this kind of data (see below), I try to create a new column IRISCOM based on a conditional test with mutate().

COMMUNE|IRIS|NB
35360|353600101|45
35361|ZZZZZZ|72

I have tried with data=mutate(data, IRISCOM= ifelse(IRIS == "ZZZZZZZZZ", COMMUNE, IRIS))

It writes correctly COMMUNE but does write 1 in place of IRIS code as expected.

I've tried some more experimentations with no success.

1
That's because IRIS is a factor; the numeric value corresponding to factor level 353600101 is 1. - Maurits Evers

1 Answers

1
votes

To fix the factor issue (see my comment above) we can do the following

library(tidyverse)
data %>%
    mutate_if(is.factor, as.character) %>%
    mutate(IRISCOM = ifelse(IRIS == "ZZZZZZ", COMMUNE, IRIS))
#  COMMUNE      IRIS NB   IRISCOM
#1   35360 353600101 45 353600101
#2   35361    ZZZZZZ 72     35361

Sample data

data <- read.table(text =
    "COMMUNE|IRIS|NB
35360|353600101|45
35361|ZZZZZZ|72", header = T, sep = "|")