Reputation: 439
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.
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
Reputation: 12074
Here's a tidyverse
solution.
"Value"
(ls(pattern = "Value")
).get
.dplyr
and tidyr
.Value_Number
into two and put the resulting values in Type
and Value_Number
.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