Populate a new column if a value is found in any column

前端 未结 3 1606
花落未央
花落未央 2021-01-25 07:36

I want to check every row in data frame. I need to check all columns in that row to see if it contains a 1, if it does I want to populate another column that summarizes if any

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-25 07:56

    Using:

    dat$imputed <- c('no','yes')[1 + (rowSums(dat == 1) > 0)]
    

    gives:

    > dat
      A B C imputed
    1 0 0 0      no
    2 0 1 1     yes
    3 1 0 0     yes
    4 0 0 0      no
    

    What this does:

    • rowSums(dat == 1) > 0 creates a logical vector indicating whether a row contains a 1
    • Adding 1 to that gives an integer vector
    • Which in turn can be used to create the appropriate vector of yes and no values.

    Used data:

    dat <- structure(list(A = c(0L, 0L, 1L, 0L), B = c(0L, 1L, 0L, 0L), C = c(0L, 1L, 0L, 0L)),
                     .Names = c("A", "B", "C"), class = "data.frame", row.names = c(NA, -4L))
    

提交回复
热议问题