将数据框中的每一列转换为单独的数据框 [英] Convert each column in dataframe to separate dataframe

查看:58
本文介绍了将数据框中的每一列转换为单独的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个包含10列的数据帧,其中10列中的每列代表一个单独的时间序列。

Say I have a dataframe with 10 columns where each of the 10 columns represents a separate timeseries.

我想将每个时间序列(或数据帧的每一列)存储在单独的数据帧中。

I'd like to store each timeseries(or each column of the dataframe) in a separate dataframe.

我尝试使用assign( columnname,df [,i]),其中i是for循环中从1到列数的变量。这导致每一列的字符向量,而我需要数据帧。

I have tried using assign("columnname", df[,i]) where i is a variable in a for loop running from 1 to number of columns. This results in character vectors of each column, where I require dataframes instead.

有什么想法可以继续吗?

Any idea how I might proceed?

推荐答案

# Create a test dataframe
df <- data.frame(c(1:3), c(3:5), c(8:10))
colnames(df) <- c("col1","col2","col3")

#### VERSION 1 ####
# Creates a new dataframe from each column, but lose the original column names in the new dataframes
for(i in 1:ncol(df))
  {assign(colnames(df)[i], data.frame(df[,i]))}

#### VERSION 2 ####
# Creates a new dataframe from each column, maintains the original column names in the new dataframes
for(i in 1:ncol(df))
{temp <- data.frame(df[,i])
 colnames(temp) <- colnames(df)[i]
 assign(colnames(df)[i], temp)
 rm(temp)
}

这篇关于将数据框中的每一列转换为单独的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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