Search code examples
rselectextract

How to extract same column twice from r dataframe


I have a dataframe with 10 columns and have created a plot which allows user to input four different values. I have used select() function for extracting columns for plot purpose. It works well using shiny, however, when the user selects same input value twice, the columns not getting selected twice. An example would be helpful which is given below.

names <- c("kamal", "vimal", "shamal")
age <- c(45,23,35)
weight <- c(50,34,42)

data <- data.frame(names, age, weight)

data_select <- data %>% select(names,age,names)

print(data_select)

Please guide me to extract same column twice, if selected by the user.


Solution

  • You could use [ from base R:

    data[c("names", "age", "names")]
       names age names.1
    1  kamal  45   kamal
    2  vimal  23   vimal
    3 shamal  35  shamal
    

    Or data.table:

    data.table(data)[, .(names, age, names)]
        names age  names
    1:  kamal  45  kamal
    2:  vimal  23  vimal
    3: shamal  35 shamal
    

    Using dplyr you could do:

    data_select <- data %>% 
      {sapply(c("names", "age", "names"), function(x) pull(., x))} %>% 
      as.data.frame()
    #    names age  names
    # 1  kamal  45  kamal
    # 2  vimal  23  vimal
    # 3 shamal  35 shamal