r-一行的最大值

时间:2014-10-02 17:17:21

标签: r type-conversion row

我需要从一行中找到最大值,不包括第一列(这是一个字符)。

我有一张桌子MDist

> MDist
          c.1. V2 V3 V4 V5 V6 V7    V8
1 repeticiones  0  0  1  1  1  2  <NA>
2         dias  0  0 12 15 20 28 sumas
3            0 NA NA NA NA NA NA     0
4            0 NA NA NA NA NA NA     0
5           12 NA NA  0  3  8 30    41
6           15 NA NA  3  0  5 26    34
7           20 NA NA  8  5  0 16    29
8           28 NA NA 15 13  8  0    36

我只保留最后一列并转置它:

> b<-data.frame(t(MDist[2:nrow(MDist), ncol(MDist)]))
> b
     X1 X2 X3 X4 X5 X6 X7
1 sumas  0  0 41 34 29 36


sapply(b,class)

      X1       X2       X3       X4       X5       X6       X7 
"factor" "factor" "factor" "factor" "factor" "factor" "factor" 

当我尝试将其转换为数字时,我得到一个满为1的向量。

> c<-as.numeric(b[1,2:ncol(b)])
> c

[1] 1 1 1 1 1 1

同样使用as.numeric(as.character))我也遇到了同样的问题:

> as.numeric(as.character(b[1,2:ncol(b)]))
[1] 1 1 1 1 1 1

我需要获得原始表(b)的每个值除以该行的最大值的行。那将是:

0 0 1 34/41 29/41 36/41

2 个答案:

答案 0 :(得分:1)

此外:

within(MDist, rowMax <- do.call(`pmax`, 
    c(MDist[sapply(MDist, is.numeric)], na.rm=TRUE)))
#              c.1. V2 V3 V4 V5 V6 V7    V8 rowMax
#1 repeticiones  0  0  1  1  1  2  <NA>      2
#2         dias  0  0 12 15 20 28 sumas     28
#3            0 NA NA NA NA NA NA     0     NA
#4            0 NA NA NA NA NA NA     0     NA
#5           12 NA NA  0  3  8 30    41     30
#6           15 NA NA  3  0  5 26    34     26
#7           20 NA NA  8  5  0 16    29     16
#8           28 NA NA 15 13  8  0    36     15

如果您要将最后一列与该列的max分开

MDist[,ncol(MDist)] <- as.numeric(as.character(MDist[, ncol(MDist)]))
MDist[,ncol(MDist)]/max(MDist[,ncol(MDist)], na.rm=TRUE)
# [1]        NA        NA 0.0000000 0.0000000 1.0000000 0.8292683 0.7073171
#[8] 0.8780488

数据

MDist <- structure(list(c.1. = structure(c(7L, 6L, 1L, 1L, 2L, 3L, 4L, 
5L), .Label = c("0", "12", "15", "20", "28", "dias", "repeticiones"
), class = "factor"), V2 = c(0L, 0L, NA, NA, NA, NA, NA, NA), 
V3 = c(0L, 0L, NA, NA, NA, NA, NA, NA), V4 = c(1L, 12L, NA, 
NA, 0L, 3L, 8L, 15L), V5 = c(1L, 15L, NA, NA, 3L, 0L, 5L, 
13L), V6 = c(1L, 20L, NA, NA, 8L, 5L, 0L, 8L), V7 = c(2L, 
28L, NA, NA, 30L, 26L, 16L, 0L), V8 = structure(c(6L, 7L, 
1L, 1L, 5L, 3L, 2L, 4L), .Label = c("0", "29", "34", "36", 
"41", "<NA>", "sumas"), class = "factor")), .Names = c("c.1.", 
"V2", "V3", "V4", "V5", "V6", "V7", "V8"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))

答案 1 :(得分:0)

我使用了lapply。它有效,但我想更好地理解为什么我不能以其他方式做到这一点。

> as.numeric(lapply(b[1,2:ncol(b)], as.character))
[1]  0  0 41 34 29 36