0

Similar questions have been asked about creating a column based on other columns. However, none seem to have a solution for my specific problem.

I am trying to create a new column that will be a mix of other columns and turned into a character. Hopefully my example below will explain what I mean.

If we have a data frame that looks like this:

dfTest <- data.frame( var = c("milk", "coffee", "honey", NA, "bread"), value = c(2 , 7, 1, 4, 10) ) > dfTest var value 1 milk 2 2 coffee 7 3 honey 1 4 <NA> 4 5 bread 10 

What I want to do is create a new column that will be a mix of both var and value. Specifically if var is not NA then I want the new column to read: varvalue. And if var is NA, then I just want the the new column entry to be the value. For example, my new data frame would look something like this:

 var value newCol 1 milk 2 milk ≤ 2 2 coffee 7 coffee ≤ 7 3 honey 1 honey ≤ 1 4 <NA> 4 4 5 bread 10 bread ≤ 10 

Any suggestions as to how I could do this?

2 Answers 2

1

You may use tidyr::unite -

tidyr::unite(dfTest, newCol, var, value, sep = ' ≤ ', na.rm = TRUE, remove = FALSE) # newCol var value #1 milk ≤ 2 milk 2 #2 coffee ≤ 7 coffee 7 #3 honey ≤ 1 honey 1 #4 4 <NA> 4 #5 bread ≤ 10 bread 10 

ifelse would also work -

transform(dfTest, newCol = ifelse(is.na(var), value, paste(var, value, sep = ' ≤ '))) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the adding the base R version. It's exactly what I need!
0

We can use

library(dplyr) library(tidyr) library(stringr) dfTest %>% mutate(var = replace_na(var, ''), newCol = str_c(var, value, sep=' <= ')) var value newCol 1 milk 2 milk <= 2 2 coffee 7 coffee <= 7 3 honey 1 honey <= 1 4 4 <= 4 5 bread 10 bread <= 10 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.