Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

r - dataframe to list by column with row names

I am trying to list elements of a dataframe (ordered by column) with row.names using dplyr

temp_df<-data.frame(c(1,3),c(2,4))
colnames(temp_df)<-c("col1","col2")
row.names(temp_df)<-c("r1","r2")
temp_df                    

require(dplyr)
temp_df%>%split(colnames(temp_df))

Goal

col1
r1 1
r2 3
col2
r1 2
r2 4
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use base-R for this, as you're simply extracting columns from a dataframe. Using 'drop=FALSE' ensures the preservation of row names. I do hope this was your intended output (a list of one-column dataframes).

#create vector of columns
mycols <- colnames(temp_df)
names(mycols) <- mycols

#extract data
res <- lapply(mycols, function(x){temp_df[,x, drop=F]})

>res
$col1
   col1
r1    1
r2    3

$col2
   col2
r1    2
r2    4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...