将data.frame列转换为向量? [英] Convert data.frame column to a vector?

查看:1092
本文介绍了将data.frame列转换为向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,例如:

I have a dataframe such as:

a1 = c(1, 2, 3, 4, 5)
a2 = c(6, 7, 8, 9, 10)
a3 = c(11, 12, 13, 14, 15)
aframe = data.frame(a1, a2, a3)

我尝试了以下操作,将其中一列转换为向量,但不起作用:

I tried the following to convert one of the columns to a vector, but it doesn't work:

avector <- as.vector(aframe['a2'])
class(avector) 
[1] "data.frame"

这是我能想到的唯一解决方案,但是我假设必须有一个更好的方法来做到这一点:

This is the only solution I could come up with, but I'm assuming there has to be a better way to do this:

class(aframe['a2']) 
[1] "data.frame"
avector = c()
for(atmp in aframe['a2']) { avector <- atmp }
class(avector)
[1] "numeric"

注意:我上面的词汇可能关闭了,所以请纠正我。我仍在学习R语言的世界。此外,对这里发生的事情的任何解释都是可以理解的(即与Python或其他某种语言有关会有所帮助!)

Note: My vocabulary above may be off, so please correct me if so. I'm still learning the world of R. Additionally, any explanation of what's going on here is appreciated (i.e. relating to Python or some other language would help!)

推荐答案

我将尽一切努力进行解释,但我敢打赌这将在注释中引起一两个澄清。

I'm going to attempt to explain this without making any mistakes, but I'm betting this will attract a clarification or two in the comments.

数据帧是一个列表。当使用列名和 [子集数据框时,得到的是 sublist (或子数据框) 。如果您想要实际的原子列,可以使用 [[,或者(在我看来)有些困惑,您可以使用 aframe [,2] 返回向量,而不是子列表。

A data frame is a list. When you subset a data frame using the name of a column and [, what you're getting is a sublist (or a sub data frame). If you want the actual atomic column, you could use [[, or somewhat confusingly (to me) you could do aframe[,2] which returns a vector, not a sublist.

因此,请尝试运行此序列,也许情况会更加清楚:

So try running this sequence and maybe things will be clearer:

avector <- as.vector(aframe['a2'])
class(avector) 

avector <- aframe[['a2']]
class(avector)

avector <- aframe[,2]
class(avector)

这篇关于将data.frame列转换为向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆