r - How to find min value of each col in df and delete previous values? -
assuming have following data frame:
x1 <- c(12:4, 5:8, na, na) x2 <- c(15:8, 9:15) x3 <- c(14:9, 10:13, na, na, na, na, na) df <- data.frame(x1, x2, x3)
how can search minimum value in each column, delete values before , fill columns nas preserve equal length? nas should added end of cols, lowest values in row nr. 1. real dfs have varying numbers of cols , rows.
the desired result is:
x1 x2 x3 1 4 8 9 2 5 9 10 . . 8 na 15 na
i'm assuming "df" actually:
df <- data.frame(x1, x2, x3)
in case can try like:
data.frame(lapply(df, function(y) { y[1:which.min(y)] <- na y })) # x1 x2 x3 # 1 na na na # 2 na na na # 3 na na na # 4 na na na # 5 na na na # 6 na na na # 7 na na 10 # 8 na na 11 # 9 na 9 12 # 10 5 10 13 # 11 6 11 na # 12 7 12 na # 13 8 13 na # 14 na 14 na # 15 na 15 na
after reading comment , edit, perhaps looking instead:
data.frame(lapply(df, function(y) { x1 <- rep(na, nrow(df)) x2 <- which.min(y):length(y) x1[seq_along(x2)] <- y[x2] x1 })) # x1 x2 x3 # 1 4 8 9 # 2 5 9 10 # 3 6 10 11 # 4 7 11 12 # 5 8 12 13 # 6 na 13 na # 7 na 14 na # 8 na 15 na # 9 na na na # 10 na na na # 11 na na na # 12 na na na # 13 na na na # 14 na na na # 15 na na na
Comments
Post a Comment