I want to a maximum value per rowname(1, 2, or A, B..) per multiple columns(samples).
I have a matrix.
id sample1 sample2 sample3 ...
1 16498 2416 12555.5
1 21282.5 3342 22202
2 18558 2308 na
2 17966 3047 na
2 398 176.5 na
3 347 227 201.5
3 604.5 284.5 300
3 517.5 283.5 330.5
3 3709 2338 5709
4 1 2 1
...
and then,
id sample1 sample2 sample3 ...
1 21282.5 3342 22202
2 18558 3047 na
3 3709 2338 5709
4 1 2 1
...
Please give me some advice on this problem. Thanks in advance!!
Another option, with data.table
:
require(data.table)
data.table(df)[, lapply(.SD, max), by=id]
# id sample1 sample2 sample3
# 1: 1 21282.5 3342 22202
# 2: 2 18558.0 3047 NA
# 3: 3 3709.0 2338 5709
Also considering na
as NA
with @akrun matrix m1
:
data.table(m1)[, lapply(.SD, max), by=id]
# id sample1 sample2 sample3
#1: 1 21282.5 3342 22202
#2: 2 18558.0 3047 NA
#3: 3 3709.0 2338 5709
#4: 4 1.0 2 1
Try
library(dplyr)
as.data.frame(m1) %>%
group_by(id)%>%
summarise_each(funs(max=max(., na.rm=TRUE)))
# id sample1 sample2 sample3
#1 1 21282.5 3342 22202
#2 2 18558.0 3047 NA
#3 3 3709.0 2338 5709
#4 4 1.0 2 1
Or
aggregate(.~id, as.data.frame(m1), FUN= max, na.rm=TRUE, na.action=NULL)
NOTE: I am guessing you have real NAs
in the dataset
m1 <- structure(c(1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 16498, 21282.5, 18558,
17966, 398, 347, 604.5, 517.5, 3709, 1, 2416, 3342, 2308, 3047,
176.5, 227, 284.5, 283.5, 2338, 2, 12555.5, 22202, NA, NA, NA,
201.5, 300, 330.5, 5709, 1), .Dim = c(10L, 4L), .Dimnames = list(
NULL, c("id", "sample1", "sample2", "sample3")))
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.