如何将R数据帧拆分为矢量(解除绑定) [英] How to split a R data frame into vectors (unbind)

查看:45
本文介绍了如何将R数据帧拆分为矢量(解除绑定)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对R还是比较陌生,并且一段时间以来一直在努力寻找解决方案。我正在尝试获取一个数据帧,并进行与rbind相反的操作,以便可以将整个数据帧(并希望保留原始数据帧)拆分为单独的向量,并使用row.names作为新数据源。变量名。

I'm relatively new to R and have been trying to find a solution to this problem for a while. I am trying to take a data frame and essentially do the reverse of rbind, so that I can split an entire data frame (and hopefully preserve the original data frame) into separate vectors, and use the row.names as the source of the new variable names.

因此,如果我有一个像这样的data.frame:

So if I have a data.frame like this:

      Col1  Col2 Col3
Row1   A     B    C
Row2   D     E    F
Row3   G     H    I

我希望最终结果是单独的向量:

I would like the end result to be separate vectors:

Row1 = A B C
Row2 = D E F
Row3 = G H I

我知道我可以对data.frame中的特定行进行子集化,但是我想要所有他们分开了。就方法论而言,我可以使用for循环将每一行移动到一个向量中,但是我不确定如何将行名分配为变量名。

I know I could subset specific rows out of the data.frame, but I want all of them separated. In terms of methodology could I use a for loop to move each row into a vector, but I wasn't exactly sure how to assign row names as variable names.

推荐答案

您可以通过 分割数据集行转换为矩阵后,将列表元素的名称( setNames )设置为'Row1:Row3'并使用 list2env 在全局环境中分配对象。

You can split the dataset by row after converting to matrix, set the names (setNames) of the list elements as 'Row1:Row3' and use list2env to assign the objects in the global environment.

 list2env(setNames(split(as.matrix(df),
        row(df)), paste0("Row",1:3)), envir=.GlobalEnv)

 Row1
 #[1] "A" "B" "C"
 Row2
 #[1] "D" "E" "F"

这篇关于如何将R数据帧拆分为矢量(解除绑定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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