MayaGans
MayaGans

Reputation: 1845

Add rows to DF based on index

I have two data frames, one with a full list of names in df_1, and another with a subset of the names and another column of values -- (note the names don't exactly match so I can't do a left join) with another column of values (b)

df_1 <- data.frame(a = c("one", "two", "one", "two"),  b = c("a", "b", "c", "b"))

    a b
1 one a
2 two b
3 one c
4 two b
df_2 <- data.frame(a = c("one_1", "two_2", "three_3", "one_4", "three_5", "two_6"))

        a
1   one_1
2   two_2
3 three_3
4   one_4
5 three_5
6   two_6

I'd like to insert the the rows containing "three" at their locations within df_1 into df_2

which(grepl('^three', df_2$c))
[1] 3 5

Step 1:

add an NA column so that the two dfs have the same column names

df_2$b <- NA

Step 2:

Now can I add df_2[3,1:2] and df_2[5,1:2] to df_1 at indexes 3 & 5?

Desired Output

  a         b
1 one       a
2 two       b
3 three_3   NA
4 one       c
5 three_5   NA
6 two       b

Upvotes: 1

Views: 39

Answers (1)

akrun
akrun

Reputation: 887981

We can use invert argument in grep to create the index, extract the values from 'df_1' and update that based on the index to create the column in 'df_2'

i1 <- grep('^three', df_2$a, invert = TRUE)
df_2$b[i1] <- as.character(df_1$b)
df_2
#        a    b
#1   one_1    a
#2   two_2    b
#3 three_3 <NA>
#4   one_4    c
#5 three_5 <NA>
#6   two_6    b

Upvotes: 1

Related Questions