How to replace text elements with a condition in r

I would like to replace the elements separated by "/", matching the text in the columns "X" or "Y", respectively, "x" or "y", but ignoring the "-".

df <- data.frame("X"=c("A","AB","CD","E","T"), "Y"=c("AT","A","CDCD","F","A"), "R1"=c("A/A","AB/AB","CD/CD","E/E","-/-"), "R2"=c("A/AT","AB/AB","CD/CDCD","F/F","T/T"), "R3"=c("AT/AT","A/AB","CDCD/CDCD","E/F","A/T"), "R4"=c("AT/A","A/A","-/-","F/E","T/A"), "R5"=c("-/-","A/AB","CDCD/CD","F/F","A/A"), "R6"=c("A/A","-/-","CD/CD","E/E","-/-")) 

Expected Result:

 XY R1 R2 R3 R4 R5 R6 A AT x/xx/yy/yy/x -/- x/x AB A x/xx/xy/xy/yy/x -/- CD CDCD x/xx/yy/y -/- y/xx/x EF x/xy/yx/yy/xy/yx/x TA -/- x/xy/xx/yy/y -/- 

I do not know how to do this in an effective way. I appreciate any help.

+2
source share
2 answers

A very difficult problem! Here is one solution:

 df[,3:ncol(df)] <- t(apply(df,1,function(R) sapply(strsplit(R[3:ncol(df)],'/'),function(S) paste0(gsub(paste0('^',R[1],'$'),'x',gsub(paste0('^',R[2],'$'),'y',S)),collapse='/')))); df; ## XY R1 R2 R3 R4 R5 R6 ## 1 A AT x/xx/yy/yy/x -/- x/x ## 2 AB A x/xx/xy/xy/yy/x -/- ## 3 CD CDCD x/xx/yy/y -/- y/xx/x ## 4 EF x/xy/yx/yy/xy/yx/x ## 5 TA -/- x/xy/xx/yy/y -/- 
+2
source

Here is one way: dplyr and stringr .

 library(dplyr) library(stringr) df[] <- lapply(df, as.character) df %>% rowwise() %>% do({ vars <- c(.$X, .$Y) # ordering gives precedence to longer vars replacements <- setNames(c('x', 'y'), vars)[order(nchar(vars), decreasing=TRUE)] setNames(data.frame(.[1:2], as.list(str_replace_all(unlist(tail(., -2)), replacements))), names(.)) }) # XY R1 R2 R3 R4 R5 R6 # 1 A AT x/xx/yy/yy/x -/- x/x # 2 AB A x/xx/xy/xy/yy/x -/- # 3 CD CDCD x/xx/yy/y -/- y/xx/x # 4 EF x/xy/yx/yy/xy/yx/x # 5 TA -/- x/xy/xx/yy/y -/- 
+1
source

All Articles