1

how do I change a value of a dataframe, based on another dataframe with different column names? I have Table 1 and Table 2, and would like to produce the Desired outcome as stated below.

I would like to change Number column of table 1, if Index of table 1 exists in Alphabet of Table2, without the use of if else as my dataframe is large.

Table 1)

Index Number
A 1
B 2
C 3
D 4

Table 2)

Alphabet Integer
B 25
C 30

Desired Output:

Index Number
A 1
B 25
C 30
D 4
user438383
  • 5,716
  • 8
  • 28
  • 43
nubprog
  • 31
  • 3
  • What are the criteria? In other words, looking at your desired output that could mean either 1) You want all in Table 1 and replace the values from Table 2 if higher or 2) You want all from Table 2 and append with those letters from Table 1 not prensent in Table 2. This will give just on this sample the same outcome, but is essential to know. – Merijn van Tilborg Jan 19 '22 at 15:29
  • Hi, thank you for the reply. I would like to change Number column of table 1, if Index of table 1 exists in Alphabet of Table2. – nubprog Jan 19 '22 at 15:31
  • 2
    Does this answer your question? [Replace values in a dataframe based on lookup table](https://stackoverflow.com/questions/35636315/replace-values-in-a-dataframe-based-on-lookup-table) – divibisan Jan 19 '22 at 15:39

1 Answers1

2

What's the issue with using ifelse() on a large dataframe with simple replacement?

df1 <- data.frame(Index = LETTERS[1:4], 
                  Number = 1:4)
df2 <- data.frame(Alphabet = c("B", "C"),
                  Integer = c(25, 30))

df1$Number2 <- ifelse(df1$Index %in% df2$Alphabet, df2$Integer, df1$Number)
df1
#>   Index Number Number2
#> 1     A      1       1
#> 2     B      2      30
#> 3     C      3      25
#> 4     D      4       4

Perhaps if you are concerned with incorrect indexing when using ifelse(), you could use merge() like this:

merge(df1, df2, by.x = "Index", by.y = "Alphabet", all.x = TRUE)
#>   Index Number Integer
#> 1     A      1      NA
#> 2     B      2      25
#> 3     C      3      30
#> 4     D      4      NA
Skaqqs
  • 4,010
  • 1
  • 7
  • 21