R, relating columns to row

前端 未结 2 358
别那么骄傲
别那么骄傲 2021-01-24 16:56

I have five columns[each column name represents each candidate say..

can1 can2 can3 can4 can5

, each column has binary data(TRUE OR FALSE) and

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-24 17:49

    You could also use a simple mapply for this:

    df$new_colmn <- 
    mapply(function(x,y) {
      df[x,y]
      },
      1:nrow(df),     #row number
      df$CANDIDATES)  #corresponding candidates column
    

    Essentially for each row (x argument) you return the corresponding candidates column (y argument).

    Ouput:

    > df
       can1 can2  can3  can4  can5 CANDIDATES new_colmn
    1  TRUE TRUE FALSE  TRUE FALSE       can2      TRUE
    2 FALSE TRUE FALSE FALSE FALSE       can4     FALSE
    3 FALSE TRUE  TRUE FALSE FALSE       can2      TRUE
    4  TRUE TRUE FALSE FALSE  TRUE       can1      TRUE
    

提交回复
热议问题