r - Replace all numbers in a df by median -


i replace numbers in df median of row, maintaining na values. input:

df <- 'pr_id  sample1  sample2 sample3 median             ax-1   na       120     130  125                 ax-2   na       na     na  na             ax-3   na       na     196  196' df <- read.table(text=df, header=t) 

this expected output:

df <- 'pr_id  sample1  sample2 sample3             ax-1   na       125     125                 ax-2   na       na     na             ax-3   na       na     196' df <- read.table(text=df, header=t) 

some idea accomplish that?

a possible base solution

indx <- which(!is.na(df[-1]), arr.ind = true) # find non-na incidents df[-1][indx] <- df$median[indx[, "row"]] # replace them while subsetting accordingly df$median df #   pr_id sample1 sample2 sample3 median # 1  ax-1      na     125     125    125 # 2  ax-2      na      na      na     na # 3  ax-3      na      na     196    196 

and bonus, if don't have medians yet, here's possible way calcualte them on fly

df[-1][indx] <- matrixstats::rowmedians(as.matrix(df[-1]), na.rm = true)[indx[, "row"]] 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -