当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 melt()用法及代码示例


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

用法: melt(x, na.rm, value.name)

参数:
x:要融化的数据
名称:删除 NA 的布尔值
值.名称:设置列名

范例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



相关用法


注:本文由纯净天空筛选整理自nidhi_biet大神的英文原创作品 Convert a Data Frame into a Molten Form in R Programming – melt() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。