0
votes

So I have a data frame my_df as follows

my_df <- data.frame(c("0600", "0602", "0603"))

Now I need to write ifelse statement which calculates 3 more variables and append it to a new data frame.

I am not able to find out on how to add multiple executable statements in the loop and append the calculated variables to a new data frame.

Below is my code for ifelse statement.

with(my_df, ifelse(my_df$H == "0600",{d$D <- 1+1 & d$c <- "0600"},
    ifelse(my_df$H == "0602",{d$D <- 2+1 & d$c <- "0602"},
        { d$D <- 3+1 & d$c <- "0603"}
)))

I am able to append values to new dataframe with only one executable code inside the ifloop i.e if I have only {d$D <- 1+1} it works perfectly but fails when I have multiple statements to execute.

My output data frame should be as shown below,

D    C
2    0600
3    0602
4    0603
3
ifelse() is a function. ... and you are not saving the result of the function. - jogo
@jogo Yeah I know that. So what changes will you suggest me to do so that it works? - Learner
FYI when you use with(df,...) you do not need to re-call the df to call its variables, i.e. with(df, ifelse(H == ...))... - Sotos

3 Answers

3
votes

Your syntax for ifelse is off, but I would recommend using case_when from the dplyr library here:

library(dplyr)
d$D <- case_when(
    my_df$H == "0600" ~ 1+1,
    my_df$H == "0602" ~ 2+1,
    TRUE ~ 3+1
)

d$c <- case_when(
    my_df$H == "0600" ~ "0600",
    my_df$H == "0602" ~ "0602",
    TRUE ~ "0603"
)

You could also use ifelse, but you would need nested calls to ifelse and it probably would not look good, or be very maintainable.

1
votes

Using a list:

# My data frame
my_df <- data.frame(H = c("0600", "0602", "0603"))

# My list to be used as a lookup
my_list <- list("0600" = c(D = 2, C = "0600"),
                "0602" = c(D = 3, C = "0602"),
                "0604" = c(D = 4, C = "0603"))

# Find corresponding values for 'H' 
# Then bind into a data frame
do.call(bind_rows, my_list[my_df$H])

Result:

# A tibble: 3 x 2
#   D     C    
# <chr> <chr>
# 1 2     0600 
# 2 3     0602 
# 3 4     0603 
1
votes

Using Base R

my_df <- data.frame("C" = c("0600", "0602", "0603"))
my_df$D  <- ifelse(my_df$C=="0600",2,ifelse(my_df$C=="0602",3,ifelse(my_df$C=="0603",4,NA)))