Reputation: 7
I have a problem trying to pivot text data in R from columns to rows. The data has numeric and text columns but the text columns won't pivot? I have tried using dplyr
but will use anything that works?
Code
long=pivot_longer(original, c('Col1','Col2','Col3' ))
Dput:
structure(list(Name = c("Joe", "Sanj", "Rob"), Date = c("12/08/2020",
"13/08/2020", "14/08/2020"), Col1 = c(20, 60, 40), Col2 = c("blue",
"red", "black"), Col3 = c(100, 233, 500)), row.names = c(NA,
-3L), class = c("tbl_df", "tbl", "data.frame"))
Upvotes: 0
Views: 294
Reputation: 171
Here is a data.table solution:
setDT(dt)
melt(dt, id=1:2, measure = 3:5)
Upvotes: 0
Reputation: 8880
Another solution (tidyr 1.1.1)
library(tidyverse)
pivot_longer(df,
-c(Name, Date),
values_transform = list(value = as.character))
# A tibble: 9 x 4
Name Date name value
<chr> <chr> <chr> <chr>
1 Joe 12/08/2020 Col1 20
2 Joe 12/08/2020 Col2 blue
3 Joe 12/08/2020 Col3 100
4 Sanj 13/08/2020 Col1 60
5 Sanj 13/08/2020 Col2 red
6 Sanj 13/08/2020 Col3 233
7 Rob 14/08/2020 Col1 40
8 Rob 14/08/2020 Col2 black
9 Rob 14/08/2020 Col3 500
Upvotes: 0
Reputation: 7385
You can convert all types to character
:
long %>%
mutate_all(as.character) %>%
pivot_longer(-c(Name, Date)) %>%
arrange(name) %>%
rename(`new col` = name,
Value = value)
Name Date `new col` Value
<chr> <chr> <chr> <chr>
1 Joe 12/08/2020 Col1 20
2 Sanj 13/08/2020 Col1 60
3 Rob 14/08/2020 Col1 40
4 Joe 12/08/2020 Col2 blue
5 Sanj 13/08/2020 Col2 red
6 Rob 14/08/2020 Col2 black
7 Joe 12/08/2020 Col3 100
8 Sanj 13/08/2020 Col3 233
9 Rob 14/08/2020 Col3 500
Upvotes: 1