【问题标题】:How I can make a column with some indicator?我如何制作带有一些指标的列?
【发布时间】:2019-08-07 14:30:44
【问题描述】:

我有 4 个指标和一个 id 行。我怎样才能像这样就这个指标做一个专栏:

  ID.   col1.   col2.   col3.   col4. 
   1      1       0       0       0
   2      0       0       0       1
   3      0       0       1       0

在每一行中,只有一列为 1,其他列为 0。如果 col1 为 1,则新列为 1,如果 col2 为 1,则为 2,如果 col3 为 1,则为 3,如果 col4 为 1,则为 4。

所以输出是

  ID.   col.    
   1      1      
   2      4      
   3      3     

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    一个选项是max.col

    cbind(df1[1], `col.` = max.col(df1[-1], "first"))
    #    ID. col.
    #1   1    1
    #2   2    4
    #3   3    3
    

    如果行中没有 1,则创建一个逻辑条件以将该行返回为 NA

    df1[2, 5] <- 0
    cbind(df1[1], `col.` =  max.col(df1[-1], "first") * NA^ !rowSums(df1[-1] == 1))
    

    数据

    df1 <- structure(list(ID. = 1:3, col1. = c(1L, 0L, 0L), col2. = c(0L, 
    0L, 0L), col3. = c(0L, 0L, 1L), col4. = c(0L, 1L, 0L)), 
    class = "data.frame", row.names = c(NA, 
    -3L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      • 2017-04-15
      • 2011-09-15
      • 2022-12-02
      相关资源
      最近更新 更多