Create new column with binary data or presence/absence data in R [duplicate]

我怕爱的太早我们不能终老 提交于 2021-02-05 12:28:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!