Long to wide format in R based based on one column
Try this tidyverse
approach. You data is in long format, so you have to reshape to wide. Here the code:
library(tidyverse)
#Code
df %>% group_by(ID) %>% mutate(Var=paste0('Scan_Number_',1:n())) %>%
pivot_wider(names_from = Var,values_from=Scan_Number)
Output:
# A tibble: 2 x 3
# Groups: ID [2]
ID Scan_Number_1 Scan_Number_2
<int> <chr> <chr>
1 1 E43 E56
2 2 E65 E98
Some data used:
#Data
df <- structure(list(ID = c(1L, 1L, 2L, 2L), Scan_Number = c("E43",
"E56", "E65", "E98")), class = "data.frame", row.names = c(NA,
-4L))
From long to wide for ALL the columns
You could tidyr::pivot_wider
like so:
library(tidyr)
pivot_wider(aa, names_from = type, values_from = -c(month, type))
#> # A tibble: 2 × 7
#> month value_most value_least NP_most NP_least NO_most NO_least
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 0.2 0.8 4 2 1 5
#> 2 2 1 0.1 0 6 2 4
R- How to reshape Long to Wide with multiple variables/columns
Some variables are can be better to together
df %>%
pivot_wider(id_cols = c(UserID, Full.Name, DOB, EncounterID), names_from = c(QuestionID, QName, labelnospaces), values_from = responses)
UserID Full.Name DOB EncounterID `505_Intro_Were you given any info?` `506_Care_By using this service..`
<int> <chr> <chr> <int> <chr> <chr>
1 1 John Smith 1-1-90 13 yes yes
2 2 Jane Doe 2-2-80 14 no no
`507_Out_How satisfied are you?`
<chr>
1 vsat
2 unsat
r reshape data long to wide with unknown number of columns
There's probably a more efficient way to do this, but I can't think of it right now. With two variables that need to be transformed into wide format, I think you may need to cast them separately and then merge the two together. I'd love to be proved wrong though. To do this, I create two new variables which generate a column sequence for each new ID. This will allow them to be filled with NAs easily. With the new columns, it's pretty easy to cast them into the right format and merge them together.
library(plyr)
library(reshape2)
#Assumes your data is read into a variable named x
x <- ddply(x, "IndividualID", transform,
castPropClass = paste0("PropClass", seq(length(PropClass))),
castProp = paste0("Prop", seq(length(Property))))
#Use these two new variables to cast into wide format. Wrap in merge to join together:
merge(dcast(IndividualID ~ castPropClass, value.var = "PropClass", data = x),
dcast(IndividualID ~ castProp, value.var = "Property", data = x))
#Gives you this:
IndividualID PropClass1 PropClass2 PropClass3 Prop1 Prop2 Prop3
1 1 A B <NA> X Y <NA>
2 2 A <NA> <NA> X <NA> <NA>
3 3 B C A Y W Z
This obviously doesn't have the right "order" of columns, but the data itself is right.
changing (semi)long format to wide in R
Using dplyr
and tidyr
, you can try:
df %>%
group_by(number) %>%
mutate(variable = paste0("letter", row_number())) %>%
spread(variable, letter)
number letter1 letter2 letter3
<int> <chr> <chr> <chr>
1 1 A <NA> <NA>
2 2 B C <NA>
3 3 D C A
Convert from long to wide format with multiple unique variables to other unique variables in R
We can use pivot_wider
after creating a sequence column by group
library(dplyr)
library(tidyr)
df %>%
group_by(block, species, den) %>%
mutate(rn = row_number()) %>%
ungroup %>%
pivot_wider(names_from = rn, values_from = c(area, size), names_sep = ".")
# A tibble: 8 x 9
# block species den area.1 area.2 area.3 size.1 size.2 size.3
# <fct> <fct> <fct> <int> <int> <int> <int> <int> <int>
#1 1 A 20 1 2 NA 17 18 NA
#2 1 A 50 3 4 NA 19 20 NA
#3 1 B 20 5 6 NA 21 22 NA
#4 1 B 50 7 8 NA 23 24 NA
#5 2 A 20 9 10 NA 25 26 NA
#6 2 A 50 11 12 NA 27 28 NA
#7 2 B 20 13 14 NA 29 30 NA
#8 2 B 50 15 16 17 31 32 33
reordering my reshape: long to wide with pivot_wider, different column order
It may be easier with names_glue
in pivot_wider
library(dplyr)
library(tidyr)
df %>%
pivot_wider(names_from = Set, values_from = c(Street, State),
names_glue = "{tools::toTitleCase(Set)}_{.value}") %>%
dplyr::select(ID, Name, order(readr::parse_number(names(.)[-(1:2)])) + 2)
-output
# A tibble: 3 × 8
ID Name Set1_Street Set1_State Set2_Street Set2_State Set3_Street Set3_State
<chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 A mary 123 St al 234 St nc <NA> <NA>
2 B berry 543 St fl 492 st ca 231 st md
3 C paul 492 st tx 231 st vt <NA> <NA>
Reshape data set from wide to long format grouped by variable suffix
Using reshape
we can set the cutpoints with sep=""
.
reshape(d, idvar="ID", varying=2:5, timevar="YEAR", sep="", direction="long")
# ID YEAR MI FRAC
# 1.1995 1 1995 2 3
# 7.1995 7 1995 3 10
# 10.1995 10 1995 1 2
# 1.1996 1 1996 2 4
# 7.1996 7 1996 12 1
# 10.1996 10 1996 1 1
Data
d <- structure(list(ID = c(1L, 7L, 10L), MI_1995 = c(2L, 3L, 1L),
FRAC_1995 = c(3L, 10L, 2L), MI_1996 = c(2L, 12L, 1L),
FRAC_1996 = c(4L, 1L, 1L)), row.names = c(NA, -3L),
class = "data.frame")
Related Topics
Rank a Vector Based on Order and Replace Ties with Their Average
Merge Two Dataframes If Timestamp of X Is Within Time Interval of Y
Replacing the Duplicate Values Except 1 Row in R Dataframe
How to Produce Time Series for Each Row of a Data Frame with an Unnamed First Column
How to Get the Most Frequent Level of a Categorical Variable in R
How to Get Rows, by Group, of Data Frame with Earliest Timestamp
Separate Columns with Constant Numbers and Condense Them to One Row in R Data.Frame
Cv.Glmnet' Works in Rstudio But Not Rscript
Is R Superstitious Regarding Posixct Data Type
R: How to Get the Last Element from Each Group
How to Remove Rows with All Zeros Without Using Rowsums in R
R: Expand and Fill Data Frame by Date in Series
Fill Area Between Multiple Lines in Plot
Aggregate by Specific Year in R