ArTu
ArTu

Reputation: 483

new variable multiple if/then code from sas to r

I would like to transform in R this sas code to create a new variable from an existing one:

if eta=0 then eta1=0;
if 0<eta<=4 then eta1=1;
if 4<eta<=9 then eta1=2;
if 9<eta<=14 then eta1=3;
if 14<eta<=19 then eta1=4;
if 19<eta<=24 then eta1=5;
if 24<eta<=29 then eta1=6;

.... and so on..

I tried with ifelse but here my new variable eta1 is not binary..

then i tried this:

eta1[eta<1]<- 0
eta1[eta>=1 & eta<=4]<- 1
eta1[eta>=5 & eta<=9]<- 2

and this:

pop%>%
  mutate(
    eta1=case_when(
      eta%in% c(1,2,3,4)~1,
      eta%in% c(5,6,7,8,9)~2

    )
  )

and this

pop%>%
  mutate(
    eta1=case_when(
      eta%in% c("1","2","3","4")~"1",
      eta%in% c("5","6","7","8","9")~"2"

    )
  )

but these don't work.. so I can't understand how to create it without losing infos

How can I fix it?

Thank you!

Upvotes: 0

Views: 60

Answers (2)

ArTu
ArTu

Reputation: 483

i fixed it

pop$eta1<-cut(pop$ETA, c(0,1,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,120), right=FALSE, labels=c(1:21))

Upvotes: 1

Felix T.
Felix T.

Reputation: 530

I believe a simple solution would be to create a data frame for the transformation (eta to eta1):

eta2eta1 <- data.frame(eta = 0:29,
       eta1 = c(0, rep(1, 4), rep(2, 5), rep(3, 5), rep(4, 5), rep(5, 5), rep(6, 5)))
eta eta1
0    0
1    1
2    1
3    1
4    1
5    2
6    2
7    2
8    2
9    2
[...]

And then merge the datasets using simply left_join:

# install.packages("tidyverse") # if needed
library(tidyverse)

left_join(originaldata, eta2eta1, by = "eta")

if-else statements

A more burdensome solution, in my opinion, would be to use ifelse statements, such as:

originaldata %>% 
  mutate(eta1 = ifelse(eta == 0, 0,
                ifelse(eta %in% 1:4, 1,
                ifelse(eta %in% 5:9, 2,
                ifelse(eta %in% 10:14, 3,
                ifelse(eta %in% 15:19, 4, 
                ifelse(eta %in% 20:24, 5, 6)))))))

Upvotes: 0

Related Questions