Home > Software design >  Reordering values within row r dataframe using regex
Reordering values within row r dataframe using regex

Time:08-16

This is almost certainly a duplicate, so please go ahead and shoot me down. I have searched hard and can't find it, so here goes:

I have a paired data value dataframe like this

> df <- data.frame(int1 = c("A", "B", "Ci"), int2 = c("Ca", "Cg", "A"), value = c(3,6,2))
> df
  int1 int2 value
1    A   Ca     3
2    B   Cg     6
3   Ci    A     2

I would like to reorder the values in the first two columns rowwise, searching for a regex or using %in%, such that all the all the values matching "C" are in the same column, and the all the other ones are in another column.

I'm trying to get to this:

  C_int other_int value
1    Ca         A     3
2    Cg         B     6
3    Ci         A     2

CodePudding user response:

Here is an option in base R- loop over the rows with apply, MARGIN = 1, and order the values based on the occurrence of 'C' in the elements, and assign back the ordered elements

df[1:2] <- t(apply(df[1:2], 1, function(x) x[order(!grepl("C", x))]))

-output

> df
  int1 int2 value
1   Ca    A     3
2   Cg    B     6
3   Ci    A     2
> str(df)
'data.frame':   3 obs. of  3 variables:
 $ int1 : chr  "Ca" "Cg" "Ci"
 $ int2 : chr  "A" "B" "A"
 $ value: int  3 6 2

CodePudding user response:

An alternative approach using split():

df[1:2] <- df[1:2] %>%
  t() %>%
  split(!str_detect(., "C"))
df
#>   int1 int2 value
#> 1   Ca    A     3
#> 2   Cg    B     6
#> 3   Ci    A     2

Created on 2022-08-15 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related