Home > Blockchain >  Create a new column from two other columns in R
Create a new column from two other columns in R

Time:08-08

I have two columns, I want to create a new column called class:

class_desc    class_title 
-------------------------
class 1       class 1
class 2       NA
class 4       class 2

I tried this code but it didn't work :

data_R2 <- data_R2 %>%
  mutate(class = ifelse(class_desc == class_title,
                        class-desc,
                        ifelse(class_title == class_desc,
                               class_title,
                               NA
                        ))) 

This is the desired output:

class_desc    class_title   class
-----------------------------------
class 1       class 1       class 1
class 2       NA            class 2
class 4       class 2       NA
NA            NA            NA

CodePudding user response:

class is a keyword in R, so I've called the new column class_.

I'm not quite clear what your logic is supposed to be, but in trying to guess what might lead to your output just for fun, I had strange behaviour with ifelse and NA. This is covered in this article: https://datacornering.com/ifelse-and-na-problem-in-r/.

They suggest case_when instead of nested ifelse.

I just guessed that you want class_desc if class_title is NA. Try out this scaffold for whatever your actual criteria happens to be.

data_R2 %>% mutate(class_ = case_when(
    class_desc == class_title ~ class_desc, 
    is.na(class_title) ~ class_desc,
    TRUE ~ NA_character_
    )
)

Edit: to be explicit in the default case, I've added TRUE ~ NA_character_. Just NA gave me an error, which I resolved using this page: https://github.com/tidyverse/dplyr/issues/3202

  class_desc class_title  class_
1    class 1     class 1 class 1
2    class 2        <NA> class 2
3    class 4     class 2    <NA>
4       <NA>        <NA>    <NA>
  • Related