Jen1
Jen1

Reputation: 1

Creating a new column based on specific rows in already existing column with case_when and ifelse condition

I've been struggling to find a way to reprint the values of certain rows into a new column based on a specific condition. I have a data frame that looks like this:

Name    V1  V2   V3 
name1   a   a1  yes     
name2   b   b1  yes
name3   c   c1  no
name3   d   d1  yes 

I would like to create a new column using case_when or ifelse to reprint what is in the second column if V3 is yes, or add the first and second column if V3 is no. To look something like this:

Name    V1  V2   V3 V4
name1   a   a1  yes a1  
name2   b   b1  yes a1
name3   c   c1  no  c+c1
name3   d   d1  yes d1

However, one issue Ive been running into is that my values are not all logical or all characters and are a mix of both. V3 are characters while V2 is a timestamp and V1 is a seconds time. I would appreciate any help. Thank you.

Upvotes: 0

Views: 919

Answers (1)

akrun
akrun

Reputation: 887108

We can use ifelse with transform in base R

df1 <- transform(df1, V4 = ifelse(V3 == "no", paste0(V1, "+", V2), V2))

If these are not strings, then use V1 + V2 and remove the paste0

-ouput

df1
  Name V1 V2  V3   V4
1 name1  a a1 yes   a1
2 name2  b b1 yes   b1
3 name3  c c1  no c+c1
4 name3  d d1 yes   d1

NOTE: If the columns 'V2', 'V1' are of different class, convert both to character class before doing the ifelse

df1[c("V1", "V2")] <- lapply(df1[c("V1", "V2")], as.character)

Or using dplyr

library(dplyr)
library(stringr)
df1 %>%
    mutate(V4 = case_when(V3 == "no" ~ str_c(V1, "+", V2), TRUE ~ V2))

data

df1 <- structure(list(Name = c("name1", "name2", "name3", "name3"), 
    V1 = c("a", "b", "c", "d"), V2 = c("a1", "b1", "c1", "d1"
    ), V3 = c("yes", "yes", "no", "yes")), 
class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 1

Related Questions