Electrino
Electrino

Reputation: 2900

Create new character column based on other columns in R?

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?

Upvotes: 0

Views: 360

Answers (2)

akrun
akrun

Reputation: 887971

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

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389325

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 = ' ≤ ')))

Upvotes: 1

Related Questions