且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将数据框中的每一列转换为单独的数据框

更新时间:2022-02-27 22:11:15

# 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)
}