Home > database >  Changing Character Values into Categorical
Changing Character Values into Categorical

Time:10-22

I have two habitat types, forest and bog, but need to change them into categorical values so I can plot a log function with it. I just want to code forest as 0 and habitat as 1. How would I do this?

Here is what some of my data looks like:

Site Lat Long Elev nSpp Habitat
1 TPB 42.00333 73 389 6 forest
2 TPB 42.00333 73 389 5 bog
3 HBC 42.02889 70 8 16 forest
4 HBC 42.02889 70 8 6 bog
5 CKB 42.04944 71 152 18 forest
6 CKB 42.04944 71 152 14 bog

CodePudding user response:

Base R

transform(data, Habitat =  (Habitat == "bog"))
#  Site      Lat Long Elev nSpp Habitat
#1  TPB 42.00333   73  389    6       0
#2  TPB 42.00333   73  389    5       1
#3  HBC 42.02889   70    8   16       0
#4  HBC 42.02889   70    8    6       1
#5  CKB 42.04944   71  152   18       0
#6  CKB 42.04944   71  152   14       1

The unary operator coerces the logical expression Habitat == "bog" to an integer.


Sample data

data <- read.table(text = "Site Lat Long Elev nSpp Habitat
1 TPB 42.00333 73 389 6 forest
2 TPB 42.00333 73 389 5 bog
3 HBC 42.02889 70 8 16 forest
4 HBC 42.02889 70 8 6 bog
5 CKB 42.04944 71 152 18 forest
6 CKB 42.04944 71 152 14 bog", header = T)

CodePudding user response:

You could use the following code which convert your character values to a defined value:

change <- c(forest = 0, bog = 1)
df$Habitat <- change[df$Habitat]
df
#>   Site      Lat Long Elev nSpp Habitat
#> 1  TPB 42.00333   73  389    6       0
#> 2  TPB 42.00333   73  389    5       1
#> 3  HBC 42.02889   70    8   16       0
#> 4  HBC 42.02889   70    8    6       1
#> 5  CKB 42.04944   71  152   18       0
#> 6  CKB 42.04944   71  152   14       1

Created on 2022-10-21 with reprex v2.0.2

  •  Tags:  
  • r
  • Related