我有一个数据框:
str(HSCtc_all_maxcols)
'data.frame': 12308 obs. of 11 variables:
$ AGI : Factor w/ 27747 levels "AT1G01010","AT1G01020",..: 1 6 7 8 12 14 17 18 19 20 ...
$ k2.5m : num 0 0 0 0 0 0 0 0 0 0 ...
$ k5m : num 0 -0.38 0 0 0 0 0 0 0 0 ...
$ k10m : num 0 -0.6 0 0 0 -0.27 0 0 0 0 ...
$ k15m : num 0 -0.6 0 0 0 0 0 0 0 0 ...
$ k20m : num 0 0.33 0 -0.23 0 0.85 0 0.46 0 0 ...
$ k30m : num 0 0 -0.69 0 0.49 1 0 1.03 0 -1.17 ...
$ k1h : num 1.12 0 -1.46 -0.42 0.88 1.15 0 1.62 0 -1.3 ...
$ k3h : num 1.92 -0.61 -0.9 -1.55 1.67 -0.57 -0.6 1.08 -0.91 0 ...
$ k30h : num 0.62 0 0 0 0.26 0.2 -0.32 0 1.13 0 ...
$ maxcol: chr "k9h" "k9h" "k9h" "k2.5m" ...
head(HSCtc_all_maxcols)
AGI k2.5m k5m k10m k15m k20m k30m k1h k3h k30h maxcol
1 AT1G01010 0 0.00 0.00 0.0 0.00 0.00 1.12 1.92 0.62 k9h
2 AT1G01060 0 -0.38 -0.60 -0.6 0.33 0.00 0.00 -0.61 0.00 k9h
3 AT1G01070 0 0.00 0.00 0.0 0.00 -0.69 -1.46 -0.90 0.00 k9h
4 AT1G01080 0 0.00 0.00 0.0 -0.23 0.00 -0.42 -1.55 0.00 k2.5m
5 AT1G01120 0 0.00 0.00 0.0 0.00 0.49 0.88 1.67 0.26 k3h
6 AT1G01140 0 0.00 -0.27 0.0 0.85 1.00 1.15 -0.57 0.20 k1h
对于此数据帧中的每一行,我想标识具有第一个非零值(从左到右)的列名。 例如,在上面,对于第1行,第一个非零值的列名称为k1h。对于第2行,它是k5m。
我已经编写了代码来为每一行标识具有最高值的列的名称,并且该名称显示为名为maxcol的列中每一行的最后一个值。为此的代码是:
HSCtc_all_maxcols <- HSCtc_all %>% mutate(maxcol = names(HSCtc_all[2:18])[apply(HSCtc_all[,2:18],1,which.max)])
我想在数据框中添加另一列,以便为每一行标识具有第一个非零值的列名称。
例如:
head(HSCtc_all_maxcols)
AGI k2.5m k5m k10m k15m k20m k30m k1h k3h k30h maxcol fcol
1 AT1G01010 0 0.00 0.00 0.0 0.00 0.00 1.12 1.92 0.62 k9h k1h
2 AT1G01060 0 -0.38 -0.60 -0.6 0.33 0.00 0.00 -0.61 0.00 k9h k5m
3 AT1G01070 0 0.00 0.00 0.0 0.00 -0.69 -1.46 -0.90 0.00 k9h k30m
4 AT1G01080 0 0.00 0.00 0.0 -0.23 0.00 -0.42 -1.55 0.00 k2.5m k20m
5 AT1G01120 0 0.00 0.00 0.0 0.00 0.49 0.88 1.67 0.26 k3h k30m
6 AT1G01140 0 0.00 -0.27 0.0 0.85 1.00 1.15 -0.57 0.20 k1h k10m
答案 0 :(得分:1)
这是使用max.col()
-
names(HSCtc_all[2:18])[max.col(HSCtc_all[2:18] != 0, ties.method = "first")]
答案 1 :(得分:1)
我们可以将apply
与which.max
逐行使用,以获取行中第一个非零值的索引,然后使用该索引对名称进行子集化
names(df[-1])[apply(df[-1] != 0, 1, which.max)]
#[1] "k1h" "k5m" "k30m" "k20m" "k30m" "k10m"
数据
df <- structure(list(AGI = structure(1:6, .Label = c("AT1G01010", "AT1G01060",
"AT1G01070", "AT1G01080", "AT1G01120", "AT1G01140"), class = "factor"),
k2.5m = c(0L, 0L, 0L, 0L, 0L, 0L), k5m = c(0, -0.38, 0, 0,
0, 0), k10m = c(0, -0.6, 0, 0, 0, -0.27), k15m = c(0, -0.6,
0, 0, 0, 0), k20m = c(0, 0.33, 0, -0.23, 0, 0.85), k30m = c(0,
0, -0.69, 0, 0.49, 1), k1h = c(1.12, 0, -1.46, -0.42, 0.88,
1.15), k3h = c(1.92, -0.61, -0.9, -1.55, 1.67, -0.57), k30h = c(0.62,
0, 0, 0, 0.26, 0.2), maxcol = structure(c(4L, 4L, 4L, 2L,
3L, 1L), .Label = c("k1h", "k2.5m", "k3h", "k9h"), class = "factor")),
class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))