我有下面的data.frame,我想确定最高值的位置以及索引。例如,让我们考虑下面的data.farme。
index t1 t2 t3 t4
10 1 4 7 10
20 2 5 8 11
30 3 6 9 0
40 0 0 0 0
在first step,
中,我想将data.frame.
的行加起来
index t1 t2 t3 t4
100 6 12 24 21
在second step
中,我想选择最高值的位置(t)。在本例中,这将是最高值为24的t3
。
在第三步中,我想添加列t1-t4
并标识具有最高值的索引。在本例中,这将是索引20 (最高值26)。
index t
10 22
20 26
30 18
40 0
示例数据:
df<-structure(list(index=c (10,20,30,40),
t1 = c(1, 2, 3, 0),
t2 = c(4, 5, 6, 0),
t3 = c(7, 8,9, 0),
t4 = c(10, 11, 0, 0)), row.names = c(NA,4L), class = "data.frame")
df
发布于 2020-10-01 09:53:41
在base R中,您可以在rowSums
和colSums
的帮助下完成此操作。
#Column-wise sum
df1 <- colSums(df)
df1
#index t1 t2 t3 t4
# 100 6 15 24 21
#Column name of highest value
highest_col <- names(df)[-1][which.max(df1[-1])]
highest_col
#[1] "t3"
#row-wise sum
df2 <- rowSums(df[-1])
df2
# 1 2 3 4
#22 26 18 0
#Corresponding index of highest row sum
highest_row_index <- df$index[which.max(df2)]
highest_row_index
#[1] 20
发布于 2020-10-01 09:47:44
按列排列:
df <- setDT(df)
df_c <- df[,t:=t1+t2+t3+t4][, .(index, t)]
df_c[, .(index = index[which.max(t)], t = max(t))]
按行排列:
df_r <- df[, .(index = sum(index),
t1 = sum(t1),
t2 = sum(t2),
t3 = sum(t3),
t4 = sum(t4))]
发布于 2020-10-01 10:14:20
使用dplyr
列总和:
df %>%
summarise_all(sum)
相加后选择最大值:
df %>%
summarise_all(sum) %>%
select(-index) %>%
max()
将t1-t4相加,并选择具有最大值的行:
df %>%
mutate(t = rowSums(.[2:5])) %>%
select(index,t) %>%
filter(t == max(t))
https://stackoverflow.com/questions/64152598
复制