1

I have a dataframe(1) with NA values I would like to replace with characters from another dataframe's(2) column names. I do not want one of the column names entered.

This:

Symbol <- c("A1B1", "A2B2", "A3B3")
Desc. <- c("Barcode", NA, NA)
AABB <- c("xyz-00", "2016", "0001")
YYZZ <- c("xyz-01", "2016", "0002")
df1 <- data.frame(Symbol, Desc., AABB, YYZZ)

Produces df1:

df1
    Symbol     Desc.      AABB     YYZZ
1   A1B1       Barcode    xyz-00   xyz-01
2   A2B2       NA         2016     2016
3   A3B3       NA         0001     0002

This:

Year <- c("2016", "2016")
ID <- c("001", "002")
Weight <- c(138, 170)
df2 <- data.frame(Year, ID, Weight)
rownames(df2) <- c("A1B1", "A2B2")

Produces df2:

df2
       Year    ID    Weight
A1B1   2016    001   138
A2B2   2016    002   170    

In this example, I would like to keep "Weight" from being included when I replace the NA's. The actual dataframes being used are much larger than this and the value I want to exempt will be somewhere in the middle so I would like to exempt the column name by typing it.

What I have tried is this although I know this is for numeric values:

df1[, "Desc."][is.na(df1[, "Desc."])] <- colnames(df2)[-"Weight"]

And this:

df1[, "Desc."][is.na(df1[, "Desc."])] <- colnames(df2)[!"Weight"]

Both of these produce an error stating it is an illegal argument.

The desired output would be for df1 to become

df1
    Symbol    Desc.      AABB      YYZZ
1   A1B1      Barcode    xyz-00    xyz-01
2   A2B2      Year       2016      2016
3   A3B3      ID         0001      0002
DarkHark
  • 614
  • 1
  • 6
  • 20
  • 2
    Show desired output. Some guidance: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/28481250#28481250 – Frank Aug 01 '17 at 18:36
  • 1
    I added the output as well as the code used to make the dataframes. Thanks for the guidance. – DarkHark Aug 02 '17 at 02:10

1 Answers1

2

Try this: (untested, since there's no data example.)

icol <- which(colnames(df2) == "Weight")
df1[, "Desc."][is.na(df1[, "Desc."])] <- colnames(df2)[-icol]
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66