How can R convert a data frame into a table?
In R language, you can use the melt() function from the reshape2 package to convert a data frame into a table.
First, you need to install and load the reshape2 package.
install.packages("reshape2")
library(reshape2)
Assuming there is a data frame named 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
Next, use the melt() function to transform the data frame into a table.
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
In the transformed table, variable names are stored in the variable column and their corresponding values are stored in the value column. The id.vars parameter specifies the columns to be kept unchanged, while the measure.vars parameter specifies the columns to be transformed into the table. In the example above, the ID column is kept unchanged, while the Fruit, Price, and Quantity columns are transformed into the table.