last day (14 days later) » 

4:20 PM
1
A: imputing data with median by date in R

Steven BeaupréTry: library(dplyr) df %>% group_by(date) %>% mutate(steps = ifelse(is.na(steps), median(steps, na.rm = T), steps)) Or df %>% group_by(date) %>% mutate(steps = replace(steps, is.na(steps), median(steps, na.rm = T)))

 
Thanks! Do I need to load a library? It is saying could not find function %>%
 
Try install.packages("dplyr"); library(dplyr)
 
Hi, thanks again but i need to replace it with median of steps (calculated after removing the NA values) and not median of interval. I tried the code by replacing interval with steps and the NA still remains. Editing the question to specify it
 
This doesn't work: df %>% group_by(date) %>% mutate(steps = replace(steps, is.na(steps), median(steps, na.rm = T))) ?
 
Nope :( Adding the output in the question for your reference!
 
4:20 PM
@Meeshu Are all values in steps NAs ?
 
Same output as ifelse. I have a feeling I am doing something fundamentally wrong :( Just to be sure I am not goofing this up. I should use "activity" (original datatable with NA) instead of "df" right?
 
Hi!
 
Hi
So yes you should be replacing df by activity
 
So no there are about 2k steps which are NA. Ideally in the output, all the NA values should be replaced with 0
 
4:23 PM
You asked to replace NAs with the median in your question, not zero, right ?
 
as 0 is the computed median with NA's removed and grouped by date
Yes, i need to replace the NA
 
So simply replace all NAs by zero ?
 
Umm.. I can't :( I need to make a completely reproducible, general code
its for an assignment
 
Well the code I provided should work
Are there dates where all steps are NA ?
 
I think so too!
Yes, the data has no blank values. The only NA values are in the column steps
 
4:27 PM
What I mean is that if you group by date, and replace NA with median value of steps for a given date where all steps are NAs, you will end up with NA values
 
oh ok! Let me check! I never thought of that
 
Try
df %>% group_by(date) %>% mutate(steps = ifelse(all(is.na(steps)), 0, ifelse(is.na(steps), median(steps, na.rm = T), steps)))
 
Hey! You are right
There are dates with only NA values
Thanks! :)
 
If this answer your question, consider marking it as accepted using the checkmark on the left
 
I think I will change the logic used for replacement of NA's. Calculate it using interval like you suggested
Thanks! Will do :)
 
4:36 PM
Glad it helped
 

last day (14 days later) »