简体   繁体   English

将 data.frame 的列转换为命名向量

[英]Convert column of a data.frame to Named vector

I have a data.frame that has a column which its attributes look like this:我有一个 data.frame 有一个列,其属性如下所示:

$ variable  : Named num  0.887 0.886 0.887 0.887 0.887 ...
..- attr(*, "names")= chr  "2010-01-04 00:00" "2010-01-04 00:01" "2010-01-04"

And I'm trying to reply this format in another data.frame, but I can't make the variable a Named num, I tried this:我正在尝试在另一个 data.frame 中回复这种格式,但我无法将变量设为 Named num,我尝试了以下操作:

vec = rnorm(10)
names(vec) = letters[1:10]
dd = data.frame(a = vec)
str(dd)

And also this:还有这个:

dd = data.frame(a = rnorm(10))
dd$a = setNames(dd$a, letters[1:10])
str(dd)

Which both return:两者都返回:

'data.frame':   10 obs. of  1 variable:
 $ a: num  1.623 -0.178 0.988 -0.406 -0.554 ...

Does anybody know how can I convert the column into a Named num?有人知道如何将列转换为命名编号吗?

Thank you谢谢

Here is what I could come up with.这是我能想到的。

First create the vector, then dput it to a structure instruction creating the dataframe.首先创建向量,然后dputdput创建数据帧的structure指令中。

set.seed(1234)
vec <- rnorm(10)
names(vec) <- letters[1:10]

n <- length(vec)
dd <- structure(list(a = dput(vec)), 
                class = "data.frame", row.names = c(NA, n))
str(dd)
#'data.frame':  10 obs. of  1 variable:
# $ a: Named num  -1.207 0.277 1.084 -2.346 0.429 ...
#  ..- attr(*, "names")= chr  "a" "b" "c" "d" ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM