【问题标题】:How to create a new column that follows a particular pattern?如何创建遵循特定模式的新列?
【发布时间】:2020-06-28 04:55:03
【问题描述】:

我有一个包含营养值的数据框 df。我必须创建一个新的糖尿病列,其中前两行应该是yes,第三行应该是no。

df <- data.frame(nutrition = c(199,200,350,175,226,400)) 

预期输出如下:-

# expect output
diabetic = c("Yes", "Yes", "No", "Yes", "Yes", "No")

【问题讨论】:

    标签: r dplyr data-manipulation data-wrangling


    【解决方案1】:

    您可以使用回收技术来分配新列。

    df$diabetic <- c('Yes', 'Yes', 'No')
    
    df
    #  nutrition diabetic
    #1       199      Yes
    #2       200      Yes
    #3       350       No
    #4       175      Yes
    #5       226      Yes
    #6       400       No
    

    【讨论】:

      【解决方案2】:

      我们可以通过将length.out 指定为数据集的行数来使用rep 来复制值向量,它将复制这些向量

      df$diabetic <- rep(c("Yes", "Yes", "No"), length.out = nrow(df))
      

      或者使用回收

      df  <- transform(df, diabetic = c("Yes", "Yes", "No"))
      df
      #   nutrition diabetic
      #1       199      Yes
      #2       200      Yes
      #3       350       No
      #4       175      Yes
      #5       226      Yes
      #6       400       No
      

      或者另一个选项是 seq 在创建列“是”之后,然后在特定位置插入“否”

      df$diabetic <- "Yes"
      df$diabetic[seq(3, nrow(df), by = 3)] <- "No"
      

      或者使用%%ifelse

      ifelse(seq_len(nrow(df)) %% 3 == 0, "No", "Yes")
      #[1] "Yes" "Yes" "No"  "Yes" "Yes" "No" 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-04
        • 1970-01-01
        • 2019-10-09
        • 1970-01-01
        • 2018-10-10
        • 1970-01-01
        相关资源
        最近更新 更多