Create column with conditional values to those in another column

Asked

Viewed 199 times

0

Assuming the following column with actions:

## code##

Petr

mils

oibr

I would like to know how to create another column where the values would be conditional to those of the column "code'. Example:

if codigo='petr' then nova_coluna = 'baixo risco'
if codigo='mils' then nova_coluna = 'alto risco'
if codigo='oibr' then nova_coluna = 'especulacao'
  • When you say you have a spine, this means it has a class object "data.frame" (or a table) with a column called codigo?

1 answer

1

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))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.