【问题标题】:How do you turn categorical rows into columnd?如何将分类行转换为列?
【发布时间】:2020-05-07 22:50:04
【问题描述】:

我正在尝试将 org_type 的行转换为列。有没有办法做到这一点我尝试传播,但我没有成功。有谁知道怎么做? 下面是一张图片。 r

【问题讨论】:

标签: r dataset tibble spread


【解决方案1】:

您可以使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2013-06-12
    • 2011-12-21
    相关资源
    最近更新 更多