Home > Software engineering >  Replace cells of a table based on a vector (except for blank cells and without a dictionary)
Replace cells of a table based on a vector (except for blank cells and without a dictionary)

Time:10-06

I have a table like this (the first row is header):

ID Sire Dam
EL SF NA
GN SF UJ
SF SF NA

and a vector like this:

G<-c("10325", "6788" ,"1140","6788","6789" , "14140", "6788" )

I wonder how can I replace cells of the table based on that vector (except for blank cells) to get this table (without a dictionary):

ID Sire Dam
10325 6788 NA
1140 6788 6789
14140 6788 NA

CodePudding user response:

Here is one way to do this -

tmp <- t(df)
df[] <- t(replace(tmp, !is.na(tmp), G))
df

#     ID Sire  Dam
#1 10325 6788 <NA>
#2  1140 6788 6789
#3 14140 6788 <NA>

Replacement works columnwise but you are changing the values rowwise hence transpose is necessary.

  • Related