I have data generated from a Python script where the entries look like:
Counter({'a': 3, 'b': 2})
or
Counter({'a': 4, 'b': 1, 'c': 7})
If the above are read as characters in R, how can I extract the values into a single vector or other object that R can read? So, in the second example, we would have:
c('a','a','a','a','b','c','c','c','c','c','c','c')
It's close enough to json that I think we can use jsonlite
to help:
S <- "Counter({'a': 4, 'b': 1, 'c': 7})"
gsub("'", '"', gsub("^Counter\\(|\\)$", "", S))
# [1] "{\"a\": 4, \"b\": 1, \"c\": 7}"
S2 <- jsonlite::fromJSON(gsub("'", '"', gsub("^Counter\\(|\\)$", "", S)))
S2
# $a
# [1] 4
# $b
# [1] 1
# $c
# [1] 7
rep(names(S2), times = unlist(S2))
# [1] "a" "a" "a" "a" "b" "c" "c" "c" "c" "c" "c" "c"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.