# Data encoding In a Column

Hey, I have a column where I want to replace certain values. Change (1-3) to 0 and (4-7) to 1, by using different methods. please help me with this.

Here is the sample data set:
Trump
6
6
5
4
3
5
7
6
5
2
5
7
5
1

Here are a couple different ways you can do it - `dplyr::case_when` is perfect for this. If for some reason you can't use the `tidyverse`, then you want base R's `ifelse`.

``````# Creating some dummy data
df <- data.frame(
'a' = runif(14, 1, 10),
'b' = runif(14, 1, 10),
'trump' = c(6, 6, 5, 4, 3, 5, 7, 6, 5, 2, 5, 7, 5, 1)
)

# a tidyverse solution
library(dplyr)

df_tidyverse <- df %>%
mutate(
trump = case_when(
trump %in% 1:3 ~ 0,
trump %in% 4:7 ~ 1
)
)

df_tidyverse
#>           a        b trump
#> 1  7.483554 8.645117     1
#> 2  4.250305 1.903815     1
#> 3  4.410424 7.006622     1
#> 4  4.673770 7.418713     1
#> 5  1.575785 9.354004     0
#> 6  8.395300 3.544063     1
#> 7  8.611944 3.148648     1
#> 8  9.141468 5.087943     1
#> 9  2.423060 9.207677     1
#> 10 3.756432 1.319760     0
#> 11 5.788083 1.461409     1
#> 12 5.720725 5.178590     1
#> 13 3.682570 3.484350     1
#> 14 8.618166 3.561444     0

# a base R solution
df\$trump <- ifelse(
test = df\$trump %in% 1:3,
yes = 0,
no = ifelse(
test = df\$trump %in% 4:7,
yes = 1,
no = NA_real_
)
)

df
#>           a        b trump
#> 1  7.483554 8.645117     1
#> 2  4.250305 1.903815     1
#> 3  4.410424 7.006622     1
#> 4  4.673770 7.418713     1
#> 5  1.575785 9.354004     0
#> 6  8.395300 3.544063     1
#> 7  8.611944 3.148648     1
#> 8  9.141468 5.087943     1
#> 9  2.423060 9.207677     1
#> 10 3.756432 1.319760     0
#> 11 5.788083 1.461409     1
#> 12 5.720725 5.178590     1
#> 13 3.682570 3.484350     1
#> 14 8.618166 3.561444     0
``````

Created on 2022-05-02 by the reprex package (v1.0.0)

Thanks a lot, dear. Appreciate the effort

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.