tidyverse
Spread with duplicate identifiers (using tidyverse and %>%) [duplicate]
We can use tidyverse. After grouping by ‘start_end’, ‘id’, create a sequence column ‘ind’ , then spread from ‘long’ to ‘wide’ format library(dplyr) library(tidyr) df %>% group_by(start_end, id) %>% mutate(ind = row_number()) %>% spread(start_end, date) %>% select(start, end) # id start end #* <int> <fctr> <fctr> #1 2 1994-05-01 1996-11-04 #2 4 1979-07-18 NA #3 … Read more
combine rows in data frame containing NA to make complete row
I haven’t figured out how to put the coalesce_by_column function inside the dplyr pipeline, but this works: coalesce_by_column <- function(df) { return(coalesce(df[1], df[2])) } df %>% group_by(A) %>% summarise_all(coalesce_by_column) ## A B C D E ## <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 1 2 3 2 5 ## 2 2 4 5 3 4 … Read more
What are the differences between R’s new native pipe `|>` and the magrittr pipe `%>%`?
Another difference between both of them is for the piped in values . can be used as a placeholder in magrittr‘s pipe c(“dogs”, “cats”, “rats”) %>% grepl(“at”, .) #[1] FALSE TRUE TRUE But this is not possible with R’s native pipe. c(“dogs”, “cats”, “rats”) |> grepl(“at”, .) Error in grepl(c(“dogs”, “cats”, “rats”), “at”, .) : … Read more
How to use Pivot_longer to reshape from wide-type data to long-type data with multiple variables
You can try : tidyr::pivot_longer(df, cols = -ID_IE, names_to = c(‘.value’, ‘grade’), names_pattern = ‘(.*)(\\d+)’) # A tibble: 8 x 4 # ID_IE grade BLS_tchrG ELS_tchrG # <dbl> <chr> <dbl> <dbl> #1 2135 2 1 1 #2 2135 7 1 1 #3 2101 2 0 0 #4 2101 7 2 0 #5 2103 2 0 … Read more