r语言

R语言如何将数据框转化为表

小亿
110
2024-01-09 22:10:35
栏目: 编程语言

在R语言中,可以使用reshape2包中的melt()函数将数据框转化为表。

首先,需要安装并加载reshape2包:

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

假设有一个名为df的数据框:

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()函数将数据框转化为表:

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

转化后的表中,变量名称保存在variable列中,对应的值保存在value列中。id.vars参数指定了保持不变的列,measure.vars参数指定了需要转化为表的列。在上面的例子中,ID列是保持不变的,FruitPriceQuantity列是需要转化为表的列。

0
看了该问题的人还看了