溫馨提示×

R語言如何將數(shù)據(jù)框轉(zhuǎn)化為表

小億
117
2024-01-09 22:10:35
欄目: 編程語言

在R語言中,可以使用reshape2包中的melt()函數(shù)將數(shù)據(jù)框轉(zhuǎn)化為表。

首先,需要安裝并加載reshape2包:

install.packages("reshape2")
library(reshape2)

假設(shè)有一個(gè)名為df的數(shù)據(jù)框:

df <- data.frame(
  ID = c(1, 2, 3),
  Fruit = c("Apple", "Banana", "Orange"),
  Price = c(1.2, 0.8, 0.5),
  Quantity = c(5, 3, 4)
)

df
#   ID  Fruit Price Quantity
# 1  1  Apple   1.2        5
# 2  2 Banana   0.8        3
# 3  3 Orange   0.5        4

然后,使用melt()函數(shù)將數(shù)據(jù)框轉(zhuǎn)化為表:

melted_df <- melt(df, id.vars = "ID", measure.vars = c("Fruit", "Price", "Quantity"))

melted_df
#   ID variable   value
# 1  1    Fruit   Apple
# 2  2    Fruit  Banana
# 3  3    Fruit Orange
# 4  1    Price     1.2
# 5  2    Price     0.8
# 6  3    Price     0.5
# 7  1 Quantity       5
# 8  2 Quantity       3
# 9  3 Quantity       4

轉(zhuǎn)化后的表中,變量名稱保存在variable列中,對應(yīng)的值保存在value列中。id.vars參數(shù)指定了保持不變的列,measure.vars參數(shù)指定了需要轉(zhuǎn)化為表的列。在上面的例子中,ID列是保持不變的,FruitPriceQuantity列是需要轉(zhuǎn)化為表的列。

0