[英]Create data frame from another data frame
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.在 df1 Q1(25%)、Q2(50%)、Q3(75%) 中是列名。 want to convert the above data frame df1 as below
想将上面的数据框 df1 转换如下
df2:
quant points
25 438.55
50 654.78
75 870.34
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)由reprex 包于 2022-07-07 创建 (v2.0.1)
You could use stack()
and extract the 2-digit numbers from the quant
column.您可以使用
stack()
并从quant
列中提取 2 位数字。
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
df <- data.frame("Q1(25%)" = 438.55, "Q2(50%)" = 654.78, "Q3(75%)" = 870.34,
check.names = FALSE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.