Home > Back-end >  create a column where each value is the result of an if statement in R
create a column where each value is the result of an if statement in R

Time:06-03

Hello I have a data frame where the 2nd and 3rd column have integers

head(mtcars)[,c(5,6)]

|drat |wt|
| ---|---|
|3.90|2.620|
|3.90|2.875|
|3.85|2.320|
|3.08|3.215|
|3.15|3.440|
|2.76|3.460|

The issue is that I want to add a third column in a way that in a row wise fashion, if the col2 number is greater to the col3 number, then the value on the same row will be "-". If the opposite is true (col2 is greater than col3), then the row value on the new column will be " ".

This is what I tried:

mtcars %>%
  rowwise() %>%
  mutate(strand = 
           if (drat < wt ){
             print("-"); else
               print(" ")
           })

but I got error message:

Error: unexpected '}' in " }"

Expected output:

|drat|wt|strand|
|----|--|------|
|3.90|2.620|"-"|
|3.90|2.875|"-"|
|3.85|2.320|"-"|
|3.08|3.215|" "|
|3.15|3.440|" "|
|2.76|3.460|" "|

CodePudding user response:

replace semicolon ";" with "}". and for else open a new "{" here is your code it works well:

mtcars %>%
  rowwise() %>%
  mutate(strand = 
           if (drat < wt ){
             print("-")} else{
               print(" ")
           })

CodePudding user response:

You don't need {} and ;:

head(mtcars)[,c(5,6)] %>%
  rowwise() %>%
  mutate(strand = if (drat < wt )print("-") else print(" "))
   drat    wt strand
  <dbl> <dbl> <chr> 
1  3.9   2.62       
2  3.9   2.88       
3  3.85  2.32       
4  3.08  3.22 -     
5  3.15  3.44 -     
6  2.76  3.46 - 

CodePudding user response:

Using ifelse might be easiest:

mtcars$strand <- ifelse(test = mtcars$drat < mtcars$wt, 
                        yes = " ", 
                        no = "-")

                   mpg cyl disp  hp drat    wt  qsec vs am gear carb strand
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4      -
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4      -
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1      -
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1       
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2       
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1       

CodePudding user response:

I think this suits you:

mtcars %>%
  mutate(strand = ifelse (drat < wt, '-', ' '))
  • Related