Reputation: 2690
I would like to add a column to a dataframe based on a value in a second dataframe. However, if the column is not present in the second dataframe I would like to add a default value. For example, if my second dataframe contains
> dataframe2$contents
[1] A A C A C T
I am merging on a common "id" column using:
Merged <- merge(dataframe1, dataframe2, by="id")
# I actually only need the contents column from dataframe2
This works great however, in some cases when merging the tables there will be no "contents" column in dataframe2. If that's the case I still want a contents column, but I want to fill it with "G".
Upvotes: 1
Views: 134
Reputation: 56219
Try this:
if(is.na(match("contents",colnames(Merged)))) Merged$contents<-"G"
If after merging there is no column named contents
then add column with default value "G".
Upvotes: 1