Home > Software design >  Create data frame from another data frame
Create data frame from another data frame

Time:07-08

I have below data frame

df1:
Q1(25%)  Q2(50%)    Q3(75%)
438.55   654.78     870.34

in df1 Q1(25%), Q2(50%), Q3(75%) are column names. want to convert the above data frame df1 as below

df2:
quant     points
25         438.55
50         654.78
75         870.34

CodePudding user response:

You could use stack() and extract the 2-digit numbers from the quant column.

transform(
  setNames(stack(df)[2:1], c("quant", "points")),
  quant = as.integer(regmatches(quant, regexpr("\\d{2}", quant)))
)

#   quant points
# 1    25 438.55
# 2    50 654.78
# 3    75 870.34
Data
df <- data.frame("Q1(25%)" = 438.55, "Q2(50%)" = 654.78, "Q3(75%)" = 870.34,
                 check.names = FALSE)

CodePudding user response:

You actually want to go from wide form of data to long form of data

library(dplyr)
library(tidyr)

df <- data.frame(q25 = 123, q50 = 345, q75 = 678)

df %>% 
  pivot_longer(everything(), names_to = "quant", values_to = "points")

#> # A tibble: 3 × 2
#>   quant points
#>   <chr>  <dbl>
#> 1 q25      123
#> 2 q50      345
#> 3 q75      678

Created on 2022-07-07 by the reprex package (v2.0.1)

  • Related