The following dataset is what I have now:
I want to get R code to get the following shape:
Note that: I have 20 stations and some stations do not have the WD attribute.
Regards,
Ahmad
The following dataset is what I have now:
I want to get R code to get the following shape:
Note that: I have 20 stations and some stations do not have the WD attribute.
Regards,
Ahmad
You should try looking into the pivot_wider()
function and documentation there from the tidyverse
package. The use case should match exactly what you are describing here.
Let assume we have the following data with two rows header:
c1 <- c('','','Alice','Alice','Bob','Bob')
c2 <- c('','','Cold','Flu','Cold','Flu')
c3 <- c('2014','Fall','X','','','X')
c4 <- c('2014','Winter','','X','','')
c5 <- c('2015','Fall','X','X','','X')
c6 <- c('2015','Winter','','','X','')
df <- data.frame(c1,c2,c3,c4,c5,c6)
I'd first combine the two columns into one, then melt/gather and finally separate
library(dplyr)
library(tidyr)
insert your df here
col.names <- c("Person", "Type", tail(paste(t(df[1,]),t(df[2,]),sep="."),n=-2))
df <- df[-c(1,2),]
df <- setNames(df,col.names)
df %>%
gather(Season, Value, -Person, -Type) %>%
mutate(Season = as.character(Season)) %>%
separate(Season,c("Year","Season"))
You can try using reshape2 package
Df_long <- melt(df, id.vars=c("Date", "Time"), measure.vars=c("TEMPERAT","RH","WS","WD","SOL_RAD","UV A","UV B"), variable.name="Values",value.name="Station") ```