is there a way in R to create a new column where the values in that column are dynamically found from other columns in the dataset?

Viewed 24

This is best explained with an example. In the table below I want to create a new column (col4) where the value is equal to the value in the column name referenced in col3.

set.seed(1)
data <- tibble(
  col1 = runif(10),
  col2 = runif(10),
  col3 = sample(c("col1", "col2"), 10, replace = TRUE)
)

So the desired result (manually created) would be as follows

data$col4 <- c(0.26550866, 0.37212390, 0.57285336, 0.90820779, 0.20168193, 0.89838968, 0.7176185, 0.66079779, 0.62911404, 0.7774452)
1 Answers

If you convert your data to dataframe, you can use :

data <- data.frame(data)
data$col4 <- as.numeric(data[cbind(1:nrow(data), match(data$col3, names(data)))])
data

#         col1      col2 col3      col4
#1  0.26550866 0.2059746 col1 0.2655087
#2  0.37212390 0.1765568 col1 0.3721239
#3  0.57285336 0.6870228 col1 0.5728534
#4  0.90820779 0.3841037 col1 0.9082078
#5  0.20168193 0.7698414 col1 0.2016819
#6  0.89838968 0.4976992 col1 0.8983897
#7  0.94467527 0.7176185 col2 0.7176185
#8  0.66079779 0.9919061 col1 0.6607978
#9  0.62911404 0.3800352 col1 0.6291140
#10 0.06178627 0.7774452 col2 0.7774452

Here we create row and column index to extract the data from and use cbind to create matrix.

Related