cms72
cms72

Reputation: 177

In R, how do I replace all instances of a string based on a column value

I have the following file.txt below

Column A     Column B         Column C        Column D        Column E.....
1            A                yes             yes             yes
2            A                                yes
3            A                yes                             yes
4            B                yes             yes             yes
5            B                yes                             yes
6            B                                yes             yes
7            C                yes             yes             yes
8            C                                yes            
9            D                yes                             yes

I would like to change all instances of "yes" to its respective column B value, in so that it looks like this:

Column A     Column B         Column C        Column D        Column E.....
1            A                A               A               A
2            A                                A
3            A                A                               A
4            B                B               B               B
5            B                B                               B
6            B                                B               B
7            C                C               C               C
8            C                                C            
9            D                D                               D

I have tried the following:

data <- data.frame(lapply(file.txt, function(x) { gsub("yes", file.txt$Column B, x) }))

But it changes all instances "yes" for each row into only "A" rather than its respective column B value.

Upvotes: 1

Views: 48

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388862

You can use ifelse with lapply -

file.txt[] <- lapply(file.txt,function(x) ifelse(x == 'yes', file.txt$ColumnB,x))
file.txt

Or using dplyr::across -

library(dplyr)
file.txt <- file.txt %>% mutate(across(.fns = ~ifelse(. == 'yes', ColumnB, .)))
file.txt
#  ColumnA ColumnB ColumnC ColumnD
#1       1       A       A       A
#2       2       A               A
#3       3       A       A        
#4       4       B       B       B
#5       5       B       B        
#6       6       B               B
#7       7       C       C       C
#8       8       C               C
#9       9       D       D        

Upvotes: 2

Related Questions