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

前端 未结 3 1626
花落未央
花落未央 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 08:12

    One of many solutions:

    a1 = data.frame(A = c(0,0,1,0), B = c(0,1,0,0), C = c(0,1,0,0))
    
    a1$imputed = apply(a1, 1, function(x) ifelse(any(x == 1), 'yes', 'no'))
    
      A B C imputed
    1 0 0 0      no
    2 0 1 1     yes
    3 1 0 0     yes
    4 0 0 0      no
    

提交回复
热议问题