Home > Enterprise >  How to add a string only to a subset of a character column in R
How to add a string only to a subset of a character column in R

Time:03-11

I have a dataframe similar to this below:

# A tibble: 32 × 3
  sample     IP  value
   <chr>  <chr> <dbl>
 1 prot1    -IP      0
 2 prot1   Mock      0
 3 prot2    -IP      0
 4 prot2   Mock      0
 5 prot3    -IP      0
 6 prot3   Mock      0
# … with 22 more rows

I want to add a string specified by a variable (a <- ("str") ) only in front of the -IP containing rows in the IP column, obtaining something like:

    # A tibble: 32 × 3
      sample     IP  value
       <chr>  <chr> <dbl>
     1 prot1 str-IP      0
     2 prot1   Mock      0
     3 prot2 str-IP      0
     4 prot2   Mock      0
     5 prot3 str-IP      0
     6 prot3   Mock      0
    # … with 22 more rows

I guess we can use a combination of paste and filter but I want to keep the entire dataset.

CodePudding user response:

For a precise solution, we can use sub here:

df$IP <- sub("-IP", paste0(a, "-IP"), df$IP, fixed=TRUE)

Another option, using ifelse with grepl:

df$IP <- ifelse(grepl("^-IP$", df$IP, fixed=TRUE), paste0(a, "-IP"), df$IP)
  • Related