I’ll assume you have a table with a column called codigo
with the values of the question.
Solution R base.
The following code starts by creating a column nova_coluna
all with the same value, 'baixo risco'
. Then modify each of the values corresponding to the values 'mils'
and 'oibr'
column codigo
.
dados$nova_coluna <- 'baixo risco'
dados$nova_coluna[dados$codigo == 'mils'] <- 'alto risco'
dados$nova_coluna[dados$codigo == 'oibr'] <- 'especulacao'
head(dados)
# codigo nova_coluna
#1 mils alto risco
#2 mils alto risco
#3 petr baixo risco
#4 oibr especulacao
#5 petr baixo risco
#6 petr baixo risco
Solution dplyr
.
This solution seems to be more readable, more in line with the way the question is formulated.
library(dplyr)
dados <- dados %>%
mutate(nova_coluna = case_when(
codigo == 'petr' ~ 'baixo risco',
codigo == 'mils' ~ 'alto risco',
codigo == 'oibr' ~ 'especulacao',
TRUE ~ NA_character_
))
Test data.
set.seed(1234)
n <- 20
dados <- data.frame(codigo = sample(c('petr', 'mils', 'oibr'), n, TRUE))
When you say you have a spine, this means it has a class object
"data.frame"
(or a table) with a column calledcodigo
?– Rui Barradas