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
206 views
in Technique[技术] by (71.8m points)

r - Is there a fast way to append all columns of a data frame into a single column?

I can't find a fast way to convert my data frame into a vector composed of the df columns. I have a df made of x rows per y columns and I'd like to have a vector or a list or a df (the class doesn't really matter) that is x per y rows and only 3columns of which one is that of the rownames (repeated for every column), the second is that of the listed values(data) and the third is that of the repeated col names. To better explain, I want to go from this


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

1 Reply

0 votes
by (71.8m points)

In base R :

result <- data.frame(row = rownames(df1), 
                     name = rep(names(df1), each = ncol(df1)), 
                     value = unlist(df1), row.names = NULL)

result
#  row name value
#1  n1   c1   0.1
#2  n2   c1   0.4
#3  n3   c1   0.7
#4  n1   c2   0.2
#5  n2   c2   0.5
#6  n3   c2   0.8
#7  n1   c3   0.3
#8  n2   c3   0.6
#9  n3   c3   0.9

Or using tidyrs pivot_longer :

library(dplyr)
library(tidyr)

df1 %>% rownames_to_column('row') %>% pivot_longer(cols = -row)

data

df1 <- structure(list(c1 = c(0.1, 0.4, 0.7), c2 = c(0.2, 0.5, 0.8), 
    c3 = c(0.3, 0.6, 0.9)), class = "data.frame", 
    row.names = c("n1", "n2", "n3"))

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

...