df name value 1 cat_name Bart 2 c-6ren">
gpt4 book ai didi

R数据帧到 "dictionary"避免因素列表

转载 作者:行者123 更新时间:2023-12-02 02:55:01 24 4
gpt4 key购买 nike

我有一个包含两列的数据框 df,一列包含名称,第二列包含可以是字符串或 double 值的值,例如

> df
name value
1 cat_name Bart
2 cat_age 5
3 dog_name Fred
4 dog_age 9
5 total_pet 2

I'd like to convert df into a list of named objects so I can call list$cat_name and get back a string "Bart" or list$bird_age and get back 1 as a numeric.

我试过了

> list <- split(df[, 2], df[, 1])
> list
$cat_age
[1] 5
Levels: 2 5 9 Bart Fred

$cat_name
[1] Bart
Levels: 2 5 9 Bart Fred

$dog_age
[1] 9
Levels: 2 5 9 Bart Fred

$dog_name
[1] Fred
Levels: 2 5 9 Bart Fred

$total_pet
[1] 2
Levels: 2 5 9 Bart Fred

df 转换为因素列表。这几乎是我想要的,因为 $ 运算符工作正常。但是,我并不真正习惯使用因子,我想知道是否还有其他可用的dataframe-to-list 转换。烦人的部分是为了处理字符串和数字,我们必须将因子转换回那些类型

> as.character(list$cat_name)
[1] "Bart"
> as.numeric(as.character(list$total_pet))
[1] 3

在注意到 df[, 1]df[, 2] 实际上是因素之后,我尝试使用

> list <- split(as.character(df[, 2]), df[, 1])
> list
$cat_age
[1] "5"

$cat_name
[1] "Bart"

$dog_age
[1] "9"

$dog_name
[1] "Fred"

$total_pet
[1] "2"

这几乎解决了问题,只是数字是稍后要转换的字符。我也尝试过使用 hash 对象

> h <- hash(as.vector(df[, 1]), as.vector(df[, 2]))
> l = as.list(h)
> l
$dog_age
[1] "9"

$dog_name
[1] "Fred"

$cat_age
[1] "5"

$total_pet
[1] "2"

$cat_name
[1] "Bart"

但我得到了相同的结果。

有人有什么建议吗?我是否遗漏了一些明显的东西?

坦克:)

最佳答案

我们可以使用 type.convert

library(purrr)
map(list, type.convert, as.is = TRUE)
#$cat_age
#[1] 5

#$cat_name
#[1] "Bart"

#$dog_age
#[1] 9

#$dog_name
#[1] "Fred"

#$total_pet
#[1] 2

因为这可以通过并行实现来提高效率,一种选择是 furrr 中的 future_map

library(furrr)
plan(multiprocess)
future_map(list, type.convert, as.is = TRUE)

关于R数据帧到 "dictionary"避免因素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49883809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com