【问题标题】:Keep variables type after using data frame使用数据框后保留变量类型
【发布时间】:2021-01-10 19:23:19
【问题描述】:

我正在尝试使用 R 包 clustMixType 中的 kproto() 函数对 Julia 中的混合类型数据进行聚类,但出现错误 No numeric variables in x! Try using kmodes() from package...。我的数据应该有 3 个变量:2 个连续变量和 1 个分类变量。似乎在我使用DataFrame() 之后,所有变量都变成了分类变量。有没有办法避免在使用DataFrame() 后更改变量类型,以便我有混合类型的数据(连续和分类)来使用kproto()

using RCall
@rlibrary clustMixType

# group 1 variables
x1=rand(Normal(0,3),10)
x2=rand(Normal(1,2),10)
x3=["1","1","2","2","0","1","1","2","2","0"]
g1=hcat(x1,x2,x3) 

# group 2 variables
y1=rand(Normal(0,4),10)
y2=rand(Normal(-1,6),10)
y3=["1","1","2","1","1","2","2","0","2","0"]
g2=hcat(y1,y2,y3)
 
#create the data
df0=vcat(g1,g2)
df1 = DataFrame(df0) 

#use R function
R"kproto($df1, 2)"

【问题讨论】:

    标签: dataframe julia cluster-analysis


    【解决方案1】:

    我对 R 包及其期望的输入类型一无所知,但问题可能在于如何构造用于构造 DataFrame 的数据矩阵,而不是 DataFrame 构造函数本身。

    当您连接一个数字列和一个字符串列时,Julia 会使用元素类型 Any 来生成结果矩阵:

    julia> g1=hcat(x1,x2,x3)
    10×3 Matrix{Any}:
      0.708309  -4.84767   "1"
      0.566883  -0.214217  "1"
    ...
    

    这意味着您的df0 矩阵是:

    julia> #create the data
           df0=vcat(g1,g2)
    20×3 Matrix{Any}:
      0.708309   -4.84767   "1"
      0.566883   -0.214217  "1"
    ...
    

    DataFrame 构造函数将仅仅通过这种缺乏类型信息而不是试图推断列类型。

    julia> DataFrame(df0)
    20×3 DataFrame
     Row │ x1         x2         x3  
         │ Any        Any        Any 
    ─────┼───────────────────────────
       1 │ 0.708309   -4.84767   1
       2 │ 0.566883   -0.214217  1
    ...
    

    解决此问题的一种简单方法是不要将列连接成单个矩阵,而是从列构造 DataFrame:

    julia> DataFrame([vcat(x1, y1), vcat(x2, y2), vcat(x3, y3)])
    20×3 DataFrame
     Row │ x1         x2          x3     
         │ Float64    Float64     String 
    ─────┼───────────────────────────────
       1 │  0.708309   -4.84767   1
       2 │  0.566883   -0.214217  1
    ...
    

    如您所见,我们现在在生成的 DataFrame 中有两个 Float64 数字列 x1x2

    【讨论】:

      【解决方案2】:

      作为对 Nils 的好答案的补充(因为问题确实是在构造矩阵时而不是在创建 DataFrame 时)有这个小技巧:

      julia> df = DataFrame([1 1.0 "1"; 2 2.0 "2"], [:int, :float, :string])
      2×3 DataFrame
       Row │ int  float  string
           │ Any  Any    Any
      ─────┼────────────────────
         1 │ 1    1.0    1
         2 │ 2    2.0    2
      
      julia> identity.(df)
      2×3 DataFrame
       Row │ int    float    string
           │ Int64  Float64  String
      ─────┼────────────────────────
         1 │     1      1.0  1
         2 │     2      2.0  2
      

      【讨论】:

        猜你喜欢
        • 2012-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-13
        相关资源
        最近更新 更多