Tengo algunos datos que contienen columnas numéricas:
df <- data.frame(v1 = c(0,1,2,3,4,5,6,7,8,9),
v2 = c(2,1,4,7,6,7,8,9,0,1),
v3 = c(4,1,6,7,8,9,0,1,2,3),
v4 = c(0,1,2,7,4,5,6,7,8,9),
v5 = c(0,1,6,3,6,9,8,9,0,1))
Puedo encontrar el primer valor máximo y devolver su nombre de columna usando which.max:
df$max <- colnames(df)[apply(df,1,which.max)]
En su lugar, me gustaría agregar cinco columnas nuevas e insertar VERDADERO si la columna correspondiente es el valor máximo o está ligada al valor máximo, y FALSO si no:
v1 v2 v3 v4 v5 v1max v2max v3max v4max v5max
1 0 2 4 0 0 FALSE FALSE TRUE FALSE FALSE
2 1 1 1 1 1 TRUE TRUE TRUE TRUE TRUE
3 2 4 6 2 6 FALSE FALSE TRUE FALSE TRUE
4 3 7 7 7 3 FALSE TRUE TRUE TRUE FALSE
5 4 6 8 4 6 FALSE FALSE TRUE FALSE FALSE
6 5 7 9 5 9 FALSE FALSE TRUE FALSE TRUE
7 6 8 0 6 8 FALSE TRUE FALSE FALSE TRUE
8 7 9 1 7 9 FALSE TRUE FALSE FALSE TRUE
9 8 0 2 8 0 TRUE FALSE FALSE TRUE FALSE
10 9 1 3 9 1 TRUE FALSE FALSE TRUE FALSE
¿Existe una forma sencilla de lograrlo?
Una solución simple y eficaz sería la de obtener el máximo modo de fila usando do.call
y pmax
y compararla con la trama de datos para obtener vectores lógicos que pueden ser asignados como nuevas columnas.
df[paste0(names(df), "max")] <- df == do.call(pmax, df)
df
# v1 v2 v3 v4 v5 v1max v2max v3max v4max v5max
#1 0 2 4 0 0 FALSE FALSE TRUE FALSE FALSE
#2 1 1 1 1 1 TRUE TRUE TRUE TRUE TRUE
#3 2 4 6 2 6 FALSE FALSE TRUE FALSE TRUE
#4 3 7 7 7 3 FALSE TRUE TRUE TRUE FALSE
#5 4 6 8 4 6 FALSE FALSE TRUE FALSE FALSE
#6 5 7 9 5 9 FALSE FALSE TRUE FALSE TRUE
#7 6 8 0 6 8 FALSE TRUE FALSE FALSE TRUE
#8 7 9 1 7 9 FALSE TRUE FALSE FALSE TRUE
#9 8 0 2 8 0 TRUE FALSE FALSE TRUE FALSE
#10 9 1 3 9 1 TRUE FALSE FALSE TRUE FALSE
Una solución con apply
podría ser
df[paste0(names(df), "max")] <- t(apply(df, 1, function(x) x == max(x)))
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras