Reputation: 902
I'd like to return the value of the start and end of a data frame based on the data it contains. Any suggestion is welcomed.
Data structure:
Output:
Sample data:
structure(list(ID = c(1, 2), A1 = c(1, 1), A2 = c(1, 1), A3 = c(0,
1), A4 = c(0, 1), A5 = c(0, 1)), class = c("spec_tbl_df", "tbl_df",
"tbl", "data.frame"), row.names = c(NA, -2L), spec = structure(list(
cols = list(ID = structure(list(), class = c("collector_double",
"collector")), A1 = structure(list(), class = c("collector_double",
"collector")), A2 = structure(list(), class = c("collector_double",
"collector")), A3 = structure(list(), class = c("collector_double",
"collector")), A4 = structure(list(), class = c("collector_double",
"collector")), A5 = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1L), class = "col_spec"))
Upvotes: 1
Views: 30
Reputation: 887048
Here is an option with max.col
.
max
value in a row for selected columns and specify the ties.method
as 'first' or 'last'data.frame
with the column names extracted along with the 'ID' columnstart <- names(df1)[-1][max.col(df1[-1], "first")]
end <- names(df1)[-1][max.col(df1[-1], "last")]
data.frame(ID = df1$ID, start, end)
-output
ID start end
1 1 A1 A2
2 2 A1 A5
Upvotes: 1