0

I have two dataframes:

dim(df1) = 70, 2
Item Freq
Q1    1
Q12   2
Q26   3

dim(df2) = 3780  ,  2
Item Freq
Q1         1
Q1        NA
Q1        NA
Q1        NA
Q1        NA
Q1        NA

Using the ifelse function, I am trying to take the factor of df1$Item and assign it to df2$Freq, however as you can see, only the first item is populated for each Item in df2, the rest becomes NA. The code I tried:

df2$Freq <- ifelse(df1$Item == df2$Item, df1$Freq, df1$Freq)

Is there a way to tell the function that I want all items that match populated in df2? Or is there another function that would achieve this? Thanks.

Csaba Szabo
  • 103
  • 1
  • 2
  • 10

1 Answers1

0

Another option would be (using package dplyr):

library(dplyr)

df1 <- structure(list(Item = c("Q1", "Q2", "Q3"), 
                      Freq = c(1, 3, 8)), 
                 .Names = c("Item", "Freq"),
                 row.names = c(NA, -3L),
                 class = "data.frame")


df2 <- structure(list(Item = c("Q1", "Q1", "Q1", "Q1", "Q1", "Q1", "Q1", 
                               "Q2", "Q2", "Q2", "Q2", "Q2", "Q3"), 
                      Freq = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
                               NA, NA, NA)),
                 .Names = c("Item", "Freq"), 
                 row.names = c(NA, -13L), 
                 class = "data.frame")

df2

Item Freq
1    Q1   NA
2    Q1   NA
3    Q1   NA
4    Q1   NA
5    Q1   NA
6    Q1   NA
7    Q1   NA
8    Q2   NA
9    Q2   NA
10   Q2   NA
11   Q2   NA
12   Q2   NA
13   Q3   NA

df3 <- left_join(select(df2,Item),
                 df1,
                 by="Item")
df3

Item Freq
1    Q1    1
2    Q1    1
3    Q1    1
4    Q1    1
5    Q1    1
6    Q1    1
7    Q1    1
8    Q2    3
9    Q2    3
10   Q2    3
11   Q2    3
12   Q2    3
13   Q3    8
ggsdc
  • 144
  • 2
  • 9