How to replace all NA in a dataframe using tidyr::replace_na? [duplicate]
If replace_na is not a mandatory requirement, following code will work: mtcars %>% replace(is.na(.), 0) Reference Issue: https://stackoverflow.com/a/45574804/8382207
If replace_na is not a mandatory requirement, following code will work: mtcars %>% replace(is.na(.), 0) Reference Issue: https://stackoverflow.com/a/45574804/8382207
Edit: I’m updating this answer since pivot_wider has been around for a while now and addresses the issue in this question and comments. You can now do pivot_wider( dat, id_cols=”Person”, names_from = ‘Time’, values_from = c(‘Score1’, ‘Score2’, ‘Score3’), names_glue=”{Time}.{.value}” ) to get the desired result. The original answer was dat %>% gather(temp, score, starts_with(“Score”)) %>% … Read more
Your gather line should look like: dat %>% gather(variable, date, -teacher, -pd) This says “Gather all variables except teacher and pd, calling the new key column ‘variable’ and the new value column ‘date’.” As an explanation, note the following from the help(gather) page: …: Specification of columns to gather. Use bare variable names. Select all … Read more
Here’s a possible both simple and very efficient solution using data.table library(data.table) ## v >= 1.9.6 dcast(setDT(df), month ~ student, value.var = c(“A”, “B”)) # month Amy_A Bob_A Amy_B Bob_B # 1: 1 9 8 6 5 # 2: 2 7 6 7 6 # 3: 3 6 9 8 7 Or a possible tidyr … Read more
The issue is still open, but in the meantime, especially since your data are already factored, you can use complete from “tidyr” to get what you might be looking for: library(tidyr) df %>% group_by(b) %>% summarise(count_a=length(a)) %>% complete(b) # Source: local data frame [3 x 2] # # b count_a # (fctr) (int) # 1 … Read more
This approach seems pretty natural to me: df %>% gather(key, value, -id, -time) %>% extract(key, c(“question”, “loop_number”), “(Q.\\..)\\.(.)”) %>% spread(question, value) First gather all question columns, use extract() to separate into question and loop_number, then spread() question back into the columns. #> id time loop_number Q3.2 Q3.3 #> 1 1 2009-01-01 1 0.142259203 -0.35842736 #> … Read more