How to update a dataframe column in R using joins without creating another object?

Asked

Viewed 241 times

0

Rapazeada blz?

Guy I am Newbie in R and I wonder if it is possible to update a data.frame in R by making key with another data.frame, the analogy in tsql would be this:

Update a Set a.col1 = b.col2 From tb1 to Join tb2 b On a.Chave1 = b.Chave2

Is there any function that would do that in R?

Inside the structure: tb1$col1 <- ....

Ex:

TABLES

df1 <- data.frame(Chave1 = c('A', 'A', 'C', ’D', 'E'), values1 = c('high', 'medium', 'high', 'high', 'low'))

Chave1 value 1 1 high 2 to medium 3 C high 4 D high 5 and low

df2 <- data.frame(Chave2 = c('A', 'E', 'C'), values2 = c('rich', 'Poble', 'average'))

Chave2 values2 1 A rich 2 and Poble 3 C average

RESULT

Chave1 value 1 1 A rich 2 A rich 3 C average 4 D NA 5 and Poble

1 answer

2

The ideal is to provide a reproducible example so that whoever answers can simulate what you have already tried. As you’re just arriving in the O.R., I’ll do it for you:

CREATING A REPRODUCIBLE EXAMPLE

df1 <- data.frame(chave1 = c('A', 'A', 'C', 'D', 'E'),
              valores1 = c('alto', 'médio', 'alto', 'alto', 'baixo'))

  chave1 valores1
1      A     alto
2      A    médio
3      C     alto
4      D     alto
5      E    baixo

df2 <- data.frame(chave2 = c('A', 'E', 'C'),
                  valores2 = c('rico', 'poble', 'média'))

  chave2 valores2
1      A     rico
2      E    poble
3      C    média

SOLUTION

The solution is the command merge. See how it works:

merge(x = df1, y = df2, by.x = 'chave1', by.y = 'chave2')

which results in

  chave1 valores1 valores2
1      A     alto     rico
2      A    médio     rico
3      C     alto    média
4      E    baixo    poble

dplyr

The dplyr is a package that allows you to make other types of joins. Ample documentation about that.

  • Opa vlw but that would not be the intention, I understand that with the merge it is possible to join the dataframes and then filter the columns by a select, but what I wanted is something to update the values of a column ready in R, and not need to create another object.

Browser other questions tagged

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