Jonathan Dunne Jonathan Dunne - 2 months ago 8
R Question

combining two data frames of different lengths at specific locations

I have two data frames one with seven rows the other with 2 rows. Here are the two frames:

content ChatPosition
1 This is a start line START
2 This is a middle line MIDDLE
3 This is a middle line MIDDLE
4 This is the last line END
5 This is a start line START
6 This is a middle line MIDDLE
7 This is the last line END


and

rating text_type
1 0.2324 Postive
2 0.8999 Postive


Basically I want to merge the two data frames, but I want to merge them so that the values in the rating and text_type data frame line up with values in the 1st and 5th rows of the first data frame. In other words the values from df2 should only be inserted where the ChatPosition value = "START" So i want to end up with a dataframe that looks like this:

content ChatPosition rating text_type
1 This is a start line START 0.2324 Postive
2 This is a middle line MIDDLE NA <NA>
3 This is a middle line MIDDLE NA <NA>
4 This is the last line END NA <NA>
5 This is a start line START 0.8999 Postive
6 This is a middle line MIDDLE NA <NA>
7 This is the last line END NA <NA>


I had a look around stackexchange, there seems to be a number of questions and answers related to solving a similar problem where the OP doesn't specify a specific matched criteria for the two frames to be merged. There is some useful code here but I haven't been able to extend it to solve my problem:

combining two data frames of different lengths.

I've included code below to get the two dataframes populated. If any one can help that would be much appreciated.

content <- c("This is a start line" , "This is a middle line" , "This is a middle line" ,"This is the last line" ,
"This is a start line" , "This is a middle line" , "This is the last line")
ChatPosition <- c("START" , "MIDDLE" , "MIDDLE" , "END" , "START" ,"MIDDLE" , "END")


df <- data.frame(content, ChatPosition)
df

rating <- c(0.2324, 0.8999)
text_type <- c("Postive", "Postive")
df2 <- data.frame(rating, text_type)
df2

Answer

I think you can do it most easily by creating empty columns and then filling them conditionally

df3<- df
df3
df3$rating<- NA
df3$text_type<- NA

df3$rating[df3$ChatPosition=="START"]<- df2$rating
df3$text_type[df3$ChatPosition=="START"]<- as.character(df2$text_type)

df3

Edit: In this I'm assuming that you wanted to insert the ratings in rows marked START