To create variables I suggest using dplyr package with function employment mutate
. Following are examples.
library(dplyr)
base <- data.frame(x = c(rep("076", 4), "840", "442",rep("076", 4)))
base
> base
x
1 076
2 076
3 076
4 076
5 840
6 442
7 076
8 076
9 076
10 076
- You can continue using the
ifelse
, but I prefer the structure shown here.
base1 <- base %>%
dplyr::mutate(iso_pais = ifelse(x == "076", "NACIONAL", "INTERNACIONAL"))
base1
> base1
x iso_pais
1 076 NACIONAL
2 076 NACIONAL
3 076 NACIONAL
4 076 NACIONAL
5 840 INTERNACIONAL
6 442 INTERNACIONAL
7 076 NACIONAL
8 076 NACIONAL
9 076 NACIONAL
10 076 NACIONAL
- Or you can use
case_when
of the dplyr package.
base2 <- base %>%
dplyr::mutate(iso_pais = dplyr::case_when(x == "076" ~ "NACIONAL",
x != "076" ~ "INTERNACIONAL"))
base2
> base2
x iso_pais
1 076 NACIONAL
2 076 NACIONAL
3 076 NACIONAL
4 076 NACIONAL
5 840 INTERNACIONAL
6 442 INTERNACIONAL
7 076 NACIONAL
8 076 NACIONAL
9 076 NACIONAL
10 076 NACIONAL
And depending on your problem, there are other n solutions, like this: How to create a column in R under specific conditions?
Cannot create variables like this. You must create variable
base$trs_localidade
, assign value to it by country and follow a stream or another based on its content.– Reginaldo Rigo