user2325155
user2325155

Reputation: 147

subset values including null values

I am trying to solve an problem where I am essentially trying to subset some data while inserting a 0 for data if the criteria is not met and keep certain characteristics of the data frame.

For example: I have a data set:

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

Using the following selection criteria:

Species== 'ABBI', Status== 'L'

but the crux that I have is that I need the plot information intact, therefore I need to add a row that is a 0 value if the ABBI criteria is not met. For example:

Plot    Species    Status
1A      ABBI       L
1B      0
2A      ABBI       L

Any suggestions? Thanks in advance!

Upvotes: 1

Views: 139

Answers (1)

Thomas
Thomas

Reputation: 44527

It sounds like you want something like this:

mydf <- 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)
mydf[!mydf$Species== 'ABBI' | !mydf$Status== 'L',c("Species","Status")] <- 0

> mydf
  Plot Species Status
1   1A    ABBI      L
2   1A       0      0
3   1B       0      0
4   1B       0      0
5   2A    ABBI      L

Upvotes: 1

Related Questions