问题
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
回答1:
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
来源:https://stackoverflow.com/questions/18818763/create-new-column-with-binary-data-or-presence-absence-data-in-r