cheklapkok
cheklapkok

Reputation: 439

How to store different but same type of values into a dataframe in R?

I just came across this issue and I'm not too sure how to approach it. Let say I have 2 types of values as such, it's currently being stored in R as each independent value. enter image description here

How can I create a dataframe where I can get something like:

Value_Number      Type      Value
     01            A          1
     02            A          1
     03            A          1
     04            A          1
     05            A          1
     01            B          1
     02            B          2
     03            B          3
     04            B          4
     05            B          5

Upvotes: 0

Views: 33

Answers (1)

Dan
Dan

Reputation: 12074

Here's a tidyverse solution.

  • First, I create the initial data.
  • Next, I create a data frame from these data based on their names.
    • I list the variables' names by searching for the pattern "Value" (ls(pattern = "Value")).
    • I also pull their values using get.
  • Then, I load the libraries for dplyr and tidyr.
  • I split Value_Number into two and put the resulting values in Type and Value_Number.
  • Finally, I strip Value off the front of each Type using sub.
# Initial data 
ValueA_01 <- 1
ValueA_02 <- 2
ValueA_03 <- 3
ValueA_04 <- 4
ValueA_05 <- 5
ValueB_01 <- 1
ValueB_02 <- 2
ValueB_03 <- 3
ValueB_04 <- 4
ValueB_05 <- 5

# Create data frame
df <- data.frame(Value_Number = ls(pattern = "Value"), 
                 Value = unlist(lapply(ls(pattern = "Value"), get)))

# Load library
library(dplyr)
library(tidyr)
library(magrittr)

# Separate
df %<>% 
  separate(Value_Number, c("Type", "Value_Number")) %>% 
  mutate(Type = sub("Value", "", Type))
#>    Type Value_Number Value
#> 1     A           01     1
#> 2     A           02     2
#> 3     A           03     3
#> 4     A           04     4
#> 5     A           05     5
#> 6     B           01     1
#> 7     B           02     2
#> 8     B           03     3
#> 9     B           04     4
#> 10    B           05     5

Created on 2019-02-27 by the reprex package (v0.2.1)

Upvotes: 1

Related Questions