user5864776 user5864776 - 3 months ago 9
R Question

Copy cell in a row if it matches column name

I searched for a while to try to solve this, but unfortunately couldn't find an answer.

In my dataframe, the last column contains strings which match column names. I would like to create another column that for each row returns(copies) the value that matches that column name.

For example, say my data is:

col1 <- c(1, 4, 6, 0, 5)
col2 <- c(4, 6, 7, 8, 6)
col3 <- c(0, 4, 2, 2, 1)
col4 <- c("col1", "col1", "col2", "col3", "col1")
df <- data.frame(col1, col2, col3, col4)


and what I want to achieve is col5 which copies relevant cells from each row:

col1 col2 col3 col4 col5
1 4 0 col1 1
4 6 4 col1 4
6 7 2 col2 7
0 8 2 col3 2
5 6 1 col1 5


Basically it looks at col4 and returns the value from the same row that matches that column name.

This is obviously a very simplified version of my data which is why I'd like to automate it.
I would really appreciate any help :)

Answer

We can use row/col indexing to extract the elements from the dataset to create the 'col5'.

df$col5 <- df[-4][cbind(1:nrow(df), match(as.character(df$col4), colnames(df)))]
df$col5
#[1] 1 4 7 2 5
Comments