简体   繁体   中英

Calculate column medians with NA's

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       |
+----+---------+---------+

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")

Another option is

library(dplyr)
 df %>%
     mutate_each(funs(median=.-median(., na.rm=TRUE)), -ID)

Of course it is possible.

median(df[,]$Point_A, na.rm = TRUE)

where df is the data frame, while df[,] means for all rows and columns. But, be aware that the column the specified afterwards by $Point_A. The same could be written in this notation:

median(df[,"Point_A"], na.rm = TRUE)

where once again, df[,"Point_A"] means for all rows of the column Point_A.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM