如何将分类行变成列?
How do you turn categorical rows into columnd?
我正在尝试将 org_type 的行转换为列。有没有办法做到这一点我试过传播,但我没有成功。有谁知道怎么做?
下面是一张图片。
r
您可以使用 mltools 和 data.table R 包来完成。首先,您需要将数据框转换为 data.table。然后你必须使用 mltools 的 one_hot() 函数。您可以看到我使用虚拟数据的示例。
# demo data frame
df <- data.frame(
org_name = c("A", "B", "C", "D", "E", "F"),
org_type = c("Tech", "Tech", "Business", "Business", "Bank", "Bank")
)
df
# load the libraries
library(data.table)
library(mltools)
# convert df to data.table
df_dt <- as.data.table(df)
# use one_hot specify the column name in cols
df_one_hot <- one_hot(df_dt, cols = "org_type")
df_one_hot
之前的输出:
org_name org_type
1 A Tech
2 B Tech
3 C Business
4 D Business
5 E Bank
6 F Bank
之后的输出:
org_name org_type_Bank org_type_Business org_type_Tech
1: A 0 0 1
2: B 0 0 1
3: C 0 1 0
4: D 0 1 0
5: E 1 0 0
6: F 1 0 0
我正在尝试将 org_type 的行转换为列。有没有办法做到这一点我试过传播,但我没有成功。有谁知道怎么做? 下面是一张图片。 r
您可以使用 mltools 和 data.table R 包来完成。首先,您需要将数据框转换为 data.table。然后你必须使用 mltools 的 one_hot() 函数。您可以看到我使用虚拟数据的示例。
# demo data frame
df <- data.frame(
org_name = c("A", "B", "C", "D", "E", "F"),
org_type = c("Tech", "Tech", "Business", "Business", "Bank", "Bank")
)
df
# load the libraries
library(data.table)
library(mltools)
# convert df to data.table
df_dt <- as.data.table(df)
# use one_hot specify the column name in cols
df_one_hot <- one_hot(df_dt, cols = "org_type")
df_one_hot
之前的输出:
org_name org_type
1 A Tech
2 B Tech
3 C Business
4 D Business
5 E Bank
6 F Bank
之后的输出:
org_name org_type_Bank org_type_Business org_type_Tech
1: A 0 0 1
2: B 0 0 1
3: C 0 1 0
4: D 0 1 0
5: E 1 0 0
6: F 1 0 0