📜  在 R 编程中将数据帧转换为熔体形式——melt()函数

📅  最后修改于: 2022-05-13 01:55:51.578000             🧑  作者: Mango

在 R 编程中将数据帧转换为熔体形式——melt()函数

R语言中的函数用于将s Data Frame的多列组合成一列。

示例 1:

# R program to reshape data frame
  
# Loading library
library(reshape) 
  
# Creating a data frame
a <- data.frame(id = c("1", "1", "2", "2"), 
                points = c("1", "2", "1", "2"), 
                x1 = c("5", "3", "6", "2"), 
                x2 = c("6", "5", "1", "4")) 
a
  
# Calling melt() Function
m <- melt(a, id = c("id", "points")) 
print(m) 

输出:

id points x1 x2
1  1      1  5  6
2  1      2  3  5
3  2      1  6  1
4  2      2  2  4
  id points variable value
1  1      1       x1     5
2  1      2       x1     3
3  2      1       x1     6
4  2      2       x1     2
5  1      1       x2     6
6  1      2       x2     5
7  2      1       x2     1
8  2      2       x2     4

示例 2:

# R program to reshape data frame
  
# Loading library
library(reshape2) 
  
# Calling pre-defined data set
BOD
  
# Calling melt() Function
m <- melt(BOD, variable.name = "Stat", value.name ="Data") 
print(m) 

输出:

Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8
No id variables; using all as measure variables
     Stat Data
1    Time  1.0
2    Time  2.0
3    Time  3.0
4    Time  4.0
5    Time  5.0
6    Time  7.0
7  demand  8.3
8  demand 10.3
9  demand 19.0
10 demand 16.0
11 demand 15.6
12 demand 19.8