Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate column medians with NA's

Tags:

r

na

median

I am trying to calculate the median of individual columns in R and then subtract the median value with every value in the column. The problem that I face here is I have N/A's in my column that I dont want to remove but just return them without subtracting the median. For example

ID <- c("A","B","C","D","E") 
Point_A <- c(1, NA, 3, NA, 5) 
Point_B <- c(NA, NA, 1, 3, 2)

df <- data.frame(ID,Point_A ,Point_B)

Is it possible to calculate the median of a column having N/A's? My resulting output would be

+----+---------+---------+
| ID | Point_A | Point_B |
+----+---------+---------+
| A  | -2      | NA      |
| B  | NA      | NA      |
| C  | 0       | -1      |
| D  | NA      | 1       |
| E  | 2       | 0       |
+----+---------+---------+
like image 457
Sharath Avatar asked Dec 25 '22 19:12

Sharath


2 Answers

If we talking real NA values (as per OPs comment), one could do

df[-1] <- lapply(df[-1], function(x) x - median(x, na.rm = TRUE))
df
#   ID Point_A Point_B
# 1  A      -2      NA
# 2  B      NA      NA
# 3  C       0      -1
# 4  D      NA       1
# 5  E       2       0

Or using the matrixStats package

library(matrixStats)
df[-1] <- df[-1] - colMedians(as.matrix(df[-1]), na.rm = TRUE)

When original df is

df <- structure(list(ID = structure(1:5, .Label = c("A", "B", "C", 
"D", "E"), class = "factor"), Point_A = c(1, NA, 3, NA, 5), Point_B = c(NA, 
NA, 1, 3, 2)), .Names = c("ID", "Point_A", "Point_B"), row.names = c(NA, 
-5L), class = "data.frame")
like image 193
David Arenburg Avatar answered Jan 06 '23 21:01

David Arenburg


Another option is

library(dplyr)
 df %>%
     mutate_each(funs(median=.-median(., na.rm=TRUE)), -ID)
like image 42
akrun Avatar answered Jan 06 '23 23:01

akrun