简体   繁体   English

从另一个数据框创建数据框

[英]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
Data数据
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.

相关问题 根据来自另一个数据框的行创建数据框的列 - Create columns of data frame based on rows from another data frame 根据另一个数据框中的值创建新数据框 - Create new data frame based on values from another data frame 从一个数据框的不同列创建一个新列,该条件以另一个数据框的另一列为条件 - Create a new column from different columns of one data frame conditioned on another column from another data frame 如何创建一个新表来汇总另一个数据框中的数据? - How to create a new table that summarises data from another data frame? 使用来自另一个数据框的条件创建数据子集 - Create subset of data using conditions from another data frame 创建一个循环以将数据从另一个数据帧添加到 dataframe 然后 plot 它 - Create a loop to add data to a dataframe from another data frame then plot it R - 用于创建包含来自另一个data.frame的操纵数据的data.frame的函数 - R - Function to create a data.frame containing manipulated data from another data.frame 在R中创建一个包含另一个数据帧统计信息的新数据框 - Create a new data frame in R containing statistics of another data frame 为另一个数据框中的每个唯一行创建数据框 - Create data frame for each unique row in another data frame 如何基于R中的另一个数据帧在数据帧中创建索引 - How to create an index in a data frame based on another data frame in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM