wide to long and col name into row name

拥有回忆 提交于 2021-02-05 12:29:52

问题


I have a table looks like this:

  v1 <- c("A","B","C")
  v2 <- c("E","G","")
  v3 <- c("B","C","D")
  df1 <- data.frame(v1,v2,v3)

and I want to change it to

What should I do. Please give me multiple ways if it is possible. Thanks.


回答1:


You can get the data in long format and then remove the blank values.

library(dplyr)
library(tidyr)

gather(df1, variable, value) %>% filter(value != '')

#  variable value
#1       v1     A
#2       v1     B
#3       v1     C
#4       v2     E
#5       v2     G
#6       v3     B
#7       v3     C
#8       v3     D

However, gather has been retired and replaced by pivot_longer itself.

pivot_longer(df1, cols = everything(), names_to = 'variable') %>%
    filter(value != '')

You can also use data.table for this :

library(data.table)
melt(setDT(df1), measure.vars = names(df1))[value != '']



回答2:


You can do a transpose using the built-in function t()

df2 <- data.frame(t(df1))
colnames(df2) <- row.names(df1)

df2
   1 2 3
v1 A B C
v2 E G  
v3 B C D


来源:https://stackoverflow.com/questions/64655613/wide-to-long-and-col-name-into-row-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!