user6985
user6985

Reputation: 93

How to replace text with values from another text file in R?

I have a text file with different parameters (par1 to par3 in this example)

 101    102    103    
 25     24     23      
 par1   par2     15      
 22     21     17      
 21     par3     18     
 22     30     19     

I want to replace all the parameter values (par 1 to par3) with the values from another text file. The structure of the text file looks as below with parameter in first row and values in the second row.

 par1    par2    par3    
 25     24     23    

I want to replace the parameters from the first text files with the values from the second text file in R.

Upvotes: 0

Views: 308

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389235

You can use str_replace_all by creating replacement as a named vector from df2.

replacement <- setNames(as.character(unlist(df2)), names(df2))
df1[] <- stringr::str_replace_all(as.matrix(df1), replacement)

df1
#   V1  V2  V3
#1 101 102 103
#2  25  24  23
#3  25  24  15
#4  22  21  17
#5  21  23  18
#6  22  30  19

data

df1 <- read.table(text = '101    102    103    
25     24     23      
par1   par2     15      
22     21     17      
21     par3     18     
22     30     19')   

df2 <- read.table(text = 'par1    par2    par3    
 25     24     23', header = TRUE)   

Upvotes: 0

akrun
akrun

Reputation: 887851

We can use

library(dplyr)
df[] <- coalesce(as.character(unlist(df2)[as.matrix(df)]), c(as.matrix(df)))
df <- type.convert(df, as.is = TRUE)

-output

df
   v1  v2  v3
1 101 102 103
2  25  24  23
3  25  24  15
4  22  21  17
5  21  23  18
6  22  30  19

data

df <- structure(list(v1 = c("101", "25", "par1", "22", "21", "22"), 
    v2 = c("102", "24", "par2", "21", "par3", "30"), v3 = c(103L, 
    23L, 15L, 17L, 18L, 19L)), class = "data.frame", row.names = c(NA, 
-6L))

df2 <- structure(list(par1 = 25L, par2 = 24L, par3 = 23L),
 class = "data.frame", row.names = c(NA, 
-1L))

Upvotes: 1

Related Questions