Home > Back-end >  Extracting a value based on a value of a column in R
Extracting a value based on a value of a column in R

Time:07-28

I have the below data frame

AccountNumber <- 123456

Tenure <- 3

x1<-0.890625

x2<-0.894634

x3<-0.814514

x4<-0.875413

x5<- 0.8765712

df <- data.frame(AccountNumber, Tenure,x1,x2,x3,x4,x5)

Input

Based on the Tenure column , i have to create a new column Rate . If the Tenure is equal to 3 then , then Rate will pick the value 0.814514 from the third column(x3), If Tenure is 2 then Rate will pick the value 0.894634(from column x2) and so on .

Output

CodePudding user response:

Based on Dynamic `case_when` that allows for different number of conditions and conditions itself a suggestion (you would have to change the sequence to 1:60):

library(dplyr) 
library(stringr)
library(purrr)


number_of_variables <- c(paste0("x", seq(1:3)))
  

all_conditions <- paste0("Tenure == ", seq(1:3)) %>% 
  as.list() %>% 
  purrr::set_names(number_of_variables)

code <- purrr::imap(all_conditions, ~ str_c(.x, " ~ ", .y)) %>% 
  str_c(collapse = ", ") %>% str_c("case_when(",.,")")

df %>% 
  mutate(Rate = !!parse_quo(code, env = rlang::caller_env()))

CodePudding user response:

An idea via base R can be,

mapply(function(x, y)x[y], 
      split(df[-c(1:2)], seq(nrow(df))), 
      split(df$Tenure, seq_along(df$Tenure)))

$`1.X1`
[1] 7

$`2.X3`
[1] 7

$`3.X2`
[1] 4

$`4.X3`
[1] 10

$`5.X1`
[1] 5
  •  Tags:  
  • r
  • Related