gpt4 book ai didi

r - 如何将数据帧行转换为 R 中的变量

转载 作者:行者123 更新时间:2023-12-05 03:22:49 25 4
gpt4 key购买 nike

如果我有一个 2 列 4 行的数据框,例如:

structure(list(var = c("url.loc", "radius", "jt", "post.age"), 
value = c("london", "25", "fulltime", "7")), row.names = c(NA,
-4L), spec = structure(list(cols = list(var = structure(list(), class = c("collector_character",
"collector")), value = structure(list(), class = c("collector_character",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), delim = ","), class = "col_spec"), problems = <pointer: 0x60000323fee0>, class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"))

...我将如何将其转换为 4 个变量,以便结果与以下相同:

url.loc <- "london"
radius <- "25"
jt <- "fulltime"
post.age <- "7"

我可以考虑使用 assign 和循环,但我认为有更优雅的方法,也许使用 NSE。

谢谢

最佳答案

我们可以创建一个命名的 list 并使用 list2env

library(tibble)
list2env(as.list(deframe(df1)), .GlobalEnv)

-检查

> url.loc
[1] "london"
> radius
[1] "25"

collapse

中的 %=% 是一个紧凑的选项
library(collapse)
df1$var %=% df1$value

-检查

> url.loc
[1] "london"
> radius
[1] "25"

关于r - 如何将数据帧行转换为 R 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72619242/

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