We get the index of column names that start with ‘pd’ (nm1
). Loop through those columns with lapply
, match
each column with the ‘nom’ column to get the row index. Using ifelse
, we change the NA
elements with the column values and the rest of the values from the ‘ID’ column.
nm1 <- grep('^pd', names(df1))
df1[nm1] <- lapply(df1[nm1], function(x) {
i1 <- match(x, df1[['nom']])
ifelse(is.na(i1), x, df1$ID[i1])})
data
df1 <- structure(list(ID = c(10L, 5L, 7L), nom = c("A10",
"A10C", "BC1"
), pd1 = c("A10C", "BCN", "hmn"), pd2 = c("BC1", "hJK", "hJj"
), pd3 = c("tt12", "LMK", "jkl")), .Names = c("ID", "nom", "pd1",
"pd2", "pd3"), class = "data.frame", row.names = c(NA, -3L))
0
solved How do I compare mathematical operations between values in two columns of an R data frame based on their position?