Module: Statsample::GGobi

Defined in:
lib/statsample/converters.rb

Class Method Summary collapse

Class Method Details

.out(dataset, opt = {}) ⇒ Object


128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/statsample/converters.rb', line 128

def out(dataset,opt={})
	require 'ostruct'
	default_opt = {:dataname => "Default", :description=>"", :missing=>"NA"}
	default_opt.merge! opt
	carrier=OpenStruct.new
	carrier.categorials=[]
	carrier.conversions={}
	variables_def=dataset.vectors.to_a.collect{|k|
		variable_definition(carrier,dataset[k],k)
	}.join("\n")

	indexes=carrier.categorials.inject({}) {|s,c|
		s[dataset.vectors.to_a.index(c)]=c
		s
	}
	records=""
	dataset.each_row {|c|
		indexes.each { |ik,iv|
			c[ik] = carrier.conversions[iv][c[ik]]
		}
		records << "<record>#{values_definition(c, default_opt[:missing])}</record>\n"
	}

out=<<EOC
<?xml version="1.0"?>
<!DOCTYPE ggobidata SYSTEM "ggobi.dtd">
<ggobidata count="1">
<data name="#{default_opt[:dataname]}">
<description>#{default_opt[:description]}</description>
<variables count="#{dataset.fields.size}">
#{variables_def}
</variables>
 <records count="#{dataset.cases}" missingValue="#{default_opt[:missing]}">
#{records}
</records>

</data>
</ggobidata>
EOC

out

end

.values_definition(c, missing) ⇒ Object


171
172
173
174
175
176
177
178
179
180
181
# File 'lib/statsample/converters.rb', line 171

def values_definition(c,missing)
  c.collect{|v|
    if v.nil?
      "#{missing}"
    elsif v.is_a? Numeric
      "#{v}"
    else
      "#{v.gsub(/\s+/,"_")}"
    end
  }.join(" ")
end

.variable_definition(carrier, v, name, nickname = nil) ⇒ Object

Outputs a string for a variable definition v = vector name = name of the variable nickname = nickname


186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/statsample/converters.rb', line 186

def variable_definition(carrier,v,name,nickname=nil)
	nickname = (nickname.nil? ? "" : "nickname=\"#{nickname}\"" )
	if v.type==:object or v.to_a.find {|d|  d.is_a? String }
		carrier.categorials.push(name)
		carrier.conversions[name]={}
		factors=v.factors
		out ="<categoricalvariable name=\"#{name}\" #{nickname}>\n"
		out << "<levels count=\"#{factors.size}\">\n"
		out << (1..factors.size).to_a.collect{|i|
			carrier.conversions[name][factors[i-1]]=i
			"<level value=\"#{i}\">#{(v.labels[factors[i-1]] || factors[i-1])}</level>"
		}.join("\n")
		out << "</levels>\n</categoricalvariable>\n"
		out
	elsif v.to_a.find {|d| d.is_a? Float}
		"<realvariable name=\"#{name}\" #{nickname} />"
	else
		"<integervariable name=\"#{name}\" #{nickname} />"
	end
end

.write(dataset, filename, opt = {}) ⇒ Object


123
124
125
126
127
# File 'lib/statsample/converters.rb', line 123

def write(dataset,filename,opt={})
  File.open(filename,"w") {|fp|
    fp.write(self.out(dataset,opt))
  }
end