问题
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