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

查看:54
本文介绍了将 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天全站免登陆