将一行数据帧转换为向量 [英] Convert a row of a data frame to vector
问题描述
我想要创建一个数据帧的一行中的向量。但我不想排队列名称。我尝试了几件事情,但没有运气。
这是我的数据框架:
> df< - data.frame(a = c(1,2,4,2),b = c(2,6,2,1),c = c(2.6,8.2,7.5,3))
pre>
> df
abc
1 1 2 2.6
2 2 6 8.2
3 4 2 7.5
4 2 1 3.0
我试过:
> newV< - as.vector(df [1,])
> newV
abc
1 1 2 2.6
但我真的想要一些看起来像:
> newV< - c(1,2,2.6)
> newV
[1] 1.0 2.0 2.6
任何帮助,非常感谢。
解决方案当您从数据框中提取单个行时,您将获得一行数据帧。将其转换为数字向量:
as.numeric(df [1,])
如@Roland所示,
unlist(df [1,])
将转换一个将数据帧拖放到数字向量而不丢弃名称。因此,unname(unlist(df [1,]))
是另一种稍微更明确的方式来获得相同的结果。I want to create a vector out of a row of a data frame. But I don't want to have to row & column names. I tried several things... but had no luck.
This is my data frame:
> df <- data.frame(a=c(1,2,4,2),b=c(2,6,2,1),c=c(2.6,8.2,7.5,3)) > df a b c 1 1 2 2.6 2 2 6 8.2 3 4 2 7.5 4 2 1 3.0
I tried:
> newV <- as.vector(df[1,]) > newV a b c 1 1 2 2.6
But I really want something looking like that:
> newV <- c( 1,2,2.6) > newV [1] 1.0 2.0 2.6
Any help, much appreciated.
解决方案When you extract a single row from a data frame you get a one-row data frame. Convert it to a numeric vector:
as.numeric(df[1,])
As @Roland suggests,
unlist(df[1,])
will convert the one-row data frame to a numeric vector without dropping the names. Thereforeunname(unlist(df[1,]))
is another, slightly more explicit way to get to the same result.这篇关于将一行数据帧转换为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!