user11418708
user11418708

Reputation: 902

Start and end based on raw

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:

enter image description here

Output:

enter image description here

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

Answers (1)

akrun
akrun

Reputation: 887048

Here is an option with max.col.

  1. Get the column index for the max value in a row for selected columns and specify the ties.method as 'first' or 'last'
  2. Use the index to extract the column name
  3. Create a data.frame with the column names extracted along with the 'ID' column
start <- 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

Related Questions