0

I am trying to add a column to a table where the new column, called "ID", would contain 3-5 or 3.5 or 3/5, if column 1 contains the value 3 and column 2 contains the value 5.

  • Ifelse statement would do here: `df$ID <- ifelse(df$col1==3 & df$col2==5, 3/5, 0)`. I set the second argument in the ifelse statement to 0 since you didn't explicitly specify what you want in return when your criteria is not met. I recommend you read up on how to properly post questions on SO. You want to provide some data for us to work with so that people can best help you. – On_an_island Oct 22 '21 at 21:29
  • Please provide enough code so others can better understand or reproduce the problem. – Community Oct 22 '21 at 22:04
  • @biology2021 It would help if you provided a [complete reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). However, you may be looking for something like: `df$ID <- paste(df[[1]], df[[2]], sep = "-")` if `df` is your data.frame...you could use a different argument for `sep` such as a decimal point, forward slash, etc. if desired. – Ben Oct 23 '21 at 00:02

2 Answers2

0
library(dplyr)
data %>% mutate(ID = paste0(column1,'-',column2))

you can change - with any symbol you want.

sveer
  • 427
  • 3
  • 16
0

As noted by others, an ifelseoperation will be helpful:

Toy data:

df <- data.frame(
  c1 = c(1,3,4,2,6,3,5),
  c2 = c(2,5,3,0,2,5,5)
)

df$ID <- ifelse(df$c1 == 3 & df$c2 == 5,        # condition to meet
                paste(df$c1, df$c2, sep = "/"), # action if condition == TRUE
                NA)                             # action if condition == FALSE

Result:

df
  c1 c2   ID
1  1  2 <NA>
2  3  5  3/5
3  4  3 <NA>
4  2  0 <NA>
5  6  2 <NA>
6  3  5  3/5
7  5  5 <NA>
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34