Joel B Joel B - 3 months ago 9
R Question

append a column based on rowname by referencing a value in R

I have two tables (df1 and df2)

df1

| A | B | C | D
| ------ | ------ | ------ | ------
1 | 0.870 | 0.435 | 0.968 | 0.679
2 | 0.456 | 0.259 | 0.906 | 0.467
3 | 0.298 | 0.256 | 0.457 | 0.768
4 | 0.994 | 0.987 | 0.365 | 0.765


df2

| E | F | G | H
| ------ | ------ | ------ | ------
1 | 0.870 | 0.435 | 0.968 | 0.679
2 | 0.456 | 0.259 | 0.906 | 0.467
3 | 0.298 | 0.256 | 0.457 | 0.768
4 | 0.994 | 0.987 | 0.365 | 0.765


and I would like to append which ever of the columns from df2 that appears within a meta data frame I also have to df1. The meta data frame will update as the programme runs (it uses a repeat / break function)

meta_frame

| letter |
| ------ |
1 | G |


I have this code but putting "s around the value var means it no longer works (i.e. running this with "var" replace with "G" would work)

var = meta_frame$letter
df1 <- cbind(no_time, df2[, "var"] [match(rownames(df1), rownames(df2))])

Answer

If I'm understanding your question correctly, the following code would append any columns in df2 that are listed in meta_frame to df1.

columns.to.append <- unique(meta_frame$letter)
df.new <- cbind(df1, df2[columns.to.append])
Comments