[英]Clojure: how to apply a function to hash-map values, some of which are vectors
I'm trying to change the type of the values in my hash map (the hash-map contains data imported from a csv file, which imports everything as a string, creating this problem) from string to float: 我正在尝试将哈希映射中的值类型(哈希映射包含从csv文件导入的数据,该文件将所有内容作为字符串导入,从而导致此问题)从字符串更改为float:
Example Input: 输入示例:
(def toydata {"EGFR" ["12.34" "4.45" "1.32"], "MYCN" "5.11", "ABC9" ["3.21" "1.32"]})
What I want: 我想要的是:
{"EGFR" [12.4 4.45 1.32] "MYCN" 5.11 "ABC9" [3.21 1.32]}
I found a great example here on SO by Thomas shown below, however it doesn't seem to work for map values that are vectors: 我在Thomas的SO上找到了一个很好的示例,如下所示,但是它似乎不适用于矢量映射值:
(defn remap [m f]
(reduce (fn [r [k v]] (assoc r k (apply f v))) {} m))
When I try to call this function on my map: 当我尝试在地图上调用此函数时:
(remap toydata #(Float/parseFloat %))
I get an error: 我收到一个错误:
ClassCastException clojure.lang.PersistentVector cannot be cast to java.lang.String
Can anyone help? 有人可以帮忙吗?
The problem is that the (apply fv) part of remap requires f to be a multi-arity function. 问题在于重映射的(应用fv)部分要求f是一个多函数函数。 I would change remap to be like this:
我将重新映射更改为:
(defn remap [m f]
(reduce (fn [r [k v]] (assoc r k (f v))) {} m))
and then do 然后做
(remap toydata (fn[x]
(if (coll? x) (into [] (map #(Float/parseFloat %) x)) (#(Float/parseFloat %) x))))
output: 输出:
{"MYCN" 5.11, "ABC9" [3.21 1.32], "EGFR" [12.34 4.45 1.32]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.