Names exchanged in a column: How to replace values in a column by keeping the rest of`data.frame` constant?

Asked

Viewed 541 times

2

I imported a spreadsheet where two observations came exchanged and the rest was correctly filled.

My problem can be demonstrated with the example below: the values assigned to the individual nome=="Foo" are in reality the values of the individual nome=="Bar". And vice versa (the values of Bar are stocked on the line of Foo). So, as I understand it, I would only need to reposition the names of individuals according to the correct values:

library(tidyverse)

nome <- c("Foo", "Bar", "FooBar",  "Baz")

set.seed(13)
df <- tibble(
  nome = rep(nome, 4),
  ano = rep(2015:2018, each=4),
  valor = sample(50, 16),
  valor2= sample(LETTERS, 16, replace = TRUE),
  valor3= sample(letters, 16, replace = TRUE)
) %>% arrange(nome)

print(df)
   # A tibble: 16 x 5
   nomes    ano valor valor2 valor3
   <chr>  <int> <int> <chr>  <chr> 
 1 Bar     2015    13 P      v     
 2 Baz     2015     5 R      c     
 3 Foo     2015    36 J      x     
 4 FooBar  2015    19 W      o     
 5 Bar     2016     1 O      b     
 6 Baz     2016    33 N      c     
 7 Foo     2016    45 D      l     
 8 FooBar  2016    26 R      t     
 9 Bar     2017     2 Q      f     
10 Baz     2017    35 L      p     
11 Foo     2017    37 C      p     
12 FooBar  2017    27 A      z     
13 Bar     2018    21 Q      x     
14 Baz     2018    49 K      i     
15 Foo     2018    34 I      q     
16 FooBar  2018    22 L      d  

# Como trocar SOMENTE `nomes=="Bar"` por `nomes=="Foo"` mantendo as demais colunas na mesma posição?

In the above example I could rewrite the vector of nomes, but would like to know if there is any safer and more practical way to do this. Any tips?

  • You want to invert these two variable categories nome simultaneously?

  • Yeah. Something like df$nome[df$nome=="Foo"] <- "Bar" along with df$nome[df$nome=="Bar"] <- "Foo".&#xA;

  • See if my answer answers what you want.

  • It worked out! Thank you very much!

1 answer

1


You can simultaneously recode the values with the function recode of dplyr. First, I’ll create an object data:

library(tidyverse)

nome <- c("Foo", "Bar", "FooBar",  "Baz")

data <- tibble(
  nome = rep(nome, 4),
  ano = rep(2015:2018, each=4),
  valor = sample(50, 16),
  valor2= sample(LETTERS, 16, replace = TRUE),
  valor3= sample(letters, 16, replace = TRUE)) %>%
  arrange(nome) %>% 
  print()

Now the simultaneous conversion:

data %>% 
  mutate(nome = recode(nome, Bar = 'Foo', Foo = 'Bar'))

If you prefer, create a new variable instead of overwriting the current one (nome):

data %>% 
  mutate(new = recode(nome, Bar = 'Foo', Foo = 'Bar'))

I named a new variable new, leaving the previous (nome) unchanged.

  • 1

    It was exactly the kind of solution I was looking for! Thank you so much for your help! :)

Browser other questions tagged

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