-2

The answer to the following question has been addressed more simply than this answer: Create new column with binary data based on several columns

I am trying to create a new column of binary data (presence/absence data) based on another column in R.

I want "Species_code" rows with the number 101 to produce a 1 in the new "Presence_absence" column; everything else should produce a 0.

Here is what I want the new Presence_absence column to look like:

Species_code       Presence_absence
101                1
103                0
101                1
99                 0
101                1
Community
  • 1
  • 1
user3545661
  • 21
  • 1
  • 4
  • 1
    Can you link the previous reply that didn't make sense? – Ben Bolker Sep 16 '13 at 00:22
  • The previous question was linked. Since my question is somewhat duplicated, can I delete it once I receive follow-up answers to my further questions below? I think it would be important to put Presence/Absence in the title of the other Question, however. Presence and absence data is often used in R, in Biology. – user3545661 Sep 16 '13 at 19:23
  • @ResearcherUsingR did you check the answer below? Is it not sufficient? If it's not, please post a comment below it clarifying what you expected. – Ferdinand.kraft Sep 16 '13 at 20:37

1 Answers1

4

Use ifelse:

> df <- data.frame(Species_code = c(101, 103,101,99,101)) # your data
> df$Presence_absence <- ifelse(df$Species_code==101, 1, 0) # this does the trick
> df
  Species_code Presence_absence
1          101                1
2          103                0
3          101                1
4           99                0
5          101                1
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • 2
    unless `Species_code` happens to be a factor ... you could be defensive via `df$Presence_absence <- ifelse(as.character(df$Species_code)=="101",1,0)`. Note you could use `as.numeric()` to be more compact if you wanted. – Ben Bolker Sep 16 '13 at 00:19
  • @BenBolker you are absolutely right. – Jilber Urbina Sep 16 '13 at 00:21