當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。