0

I am trying to find a way to add rows based on criteria in a data frame. I essentially want to take a data frame and insert values that are missing. Here is what I start with:

Plot    Species    Status
1A      ABBI       L
1A      PIEN       D
1B      ABBI       D
1B      PIEN       L
2A      ABBI       L

I would like the ability to search the Plot column for 1A, 2B and 3A. Since 1A is present, there would be no action, but 2B and 2B would be added to the data frame. For missing values, I will always want to enter the Plot number and 0 for everything else. The end result looking like this:

Plot    Species    Status
1A      ABBI       L
1A      PIEN       D
1B      ABBI       D
1B      PIEN       L
2A      ABBI       L
2B      0          0
3A      0          0

1 Answer 1

1

Use merge:

df <- read.table(text="Plot    Species    Status
1A      ABBI       L
1A      PIEN       D
1B      ABBI       D
1B      PIEN       L
2A      ABBI       L", header=TRUE, stringsAsFactors=FALSE)

lookfor <- data.frame(Plot=c("1A", "2B", "3A"), stringsAsFactors=FALSE)

res <- merge(df,lookfor,all=TRUE)

res[is.na(res$Species), c("Species", "Status")] <- 0

print(res)

#   Plot Species Status
# 1   1A    ABBI      L
# 2   1A    PIEN      D
# 3   1B    ABBI      D
# 4   1B    PIEN      L
# 5   2A    ABBI      L
# 6   2B       0      0
# 7   3A       0      0

However, you should consider to use NA instead of 0 to indicate missingness.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.