问题描述
我想从数据框的一行中创建一个向量.但我不想有行名和列名.我尝试了几件事......但没有运气.
I want to create a vector out of a row of a data frame. But I don't want to have to row and column names. I tried several things... but had no luck.
这是我的数据框:
> 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
我试过了:
> newV <- as.vector(df[1,])
> newV
a b c
1 1 2 2.6
但我真的想要这样的东西:
But I really want something looking like this:
> newV <- c( 1,2,2.6)
> newV
[1] 1.0 2.0 2.6
推荐答案
当您从数据框中提取一行时,您会得到一个单行数据框.将其转换为数值向量:
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,])
正如@Roland 所建议的那样,unlist(df[1,])
会将单行数据框转换为数字向量而不删除名称.因此,unname(unlist(df[1,]))
是另一种获得相同结果的更明确的方法.
As @Roland suggests, unlist(df[1,])
will convert the one-row data frame to a numeric vector without dropping the names. Therefore unname(unlist(df[1,]))
is another, slightly more explicit way to get to the same result.
正如@Josh 在下面评论的那样,如果您有一个不完全数字(字母、因子、混合...)的数据框,您需要 as.character(df[1,])
相反.
As @Josh comments below, if you have a not-completely-numeric (alphabetic, factor, mixed ...) data frame, you need as.character(df[1,])
instead.
这篇关于将数据框的一行转换为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2