【问题标题】:How to change all numbers greater than 0 in a data frame to the character "present"?如何将数据框中大于0的所有数字更改为字符“present”?
【发布时间】:2022-01-08 07:43:18
【问题描述】:

我只是有一个简单的问题,我尝试使用 mutate 来完成,但不是很成功。我有一个包含 2 行和许多列的数据框,其数值范围为 0-1000。我只想将每列中的非零数字更改为存在的单词,并将带有 0 的数字更改为不存在的单词。

我的示例数据框如下

Cat Dog
5 0
0 5

我想转向以下内容

Cat Dog
Present Absent
Absent Present

谢谢!

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    可以使用ifelse 语句:

    df1 <- structure(list(Cat = c(5L, 0L), Dog = c(0L, 5L)), 
                     class = "data.frame", row.names = c(NA, -2L))
    
    df2 <- ifelse(df1 == 0, "Absent","Present")
    # or
    df3 <- ifelse(df1 > 0, "Present", "Absent")
    

    【讨论】:

      【解决方案2】:

      我们可以创建一个逻辑矩阵,转换为数字索引,替换为基于位置索引的值向量并分配回原始数据集

      df1[] <- c("Absent", "Present")[1 + (df1 > 0)]
      

      -输出

      > df1
            Cat     Dog
      1 Present  Absent
      2  Absent Present
      

      数据

      df1 <- structure(list(Cat = c(5L, 0L), Dog = c(0L, 5L)), 
      class = "data.frame", row.names = c(NA, 
      -2L))
      

      【讨论】:

        猜你喜欢
        • 2020-05-18
        • 2022-01-15
        • 1970-01-01
        • 2019-04-26
        • 2021-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多