【问题标题】:Replace values in cells with an integer from a column用列中的整数替换单元格中的值
【发布时间】:2021-06-01 12:56:26
【问题描述】:

如果我有如下数据框:

id risk speciesA speciesB speciesC speciesD speciesE speciesF
A 40 NA NA text1 NA NA text2
B 12 NA text3 NA NA text4 NA
C 65 NA NA NA text5 NA text6

如何以编程方式将每行中出现的“文本”值替换为“风险”列中的值(在每种情况下它们可能是不同的词),以便获得以下信息?

id risk speciesA speciesB speciesC speciesD speciesE speciesF
A 40 NA NA 40 NA NA 40
B 12 NA 12 NA NA 12 NA
C 65 NA NA NA 65 NA 65

【问题讨论】:

    标签: r dataframe replace dplyr


    【解决方案1】:

    重塑、替换和重塑:

    library(dplyr)
    library(tidyr)
    
    df %>%
      pivot_longer(cols = starts_with('species')) %>%
      mutate(value = ifelse(is.na(value), NA, risk)) %>%
      pivot_wider()
    
    #  id     risk speciesA speciesB speciesC speciesD speciesE speciesF
    #  <chr> <int>    <int>    <int>    <int>    <int>    <int>    <int>
    #1 A        40       NA       NA       40       NA       NA       40
    #2 B        12       NA       12       NA       NA       12       NA
    #3 C        65       NA       NA       NA       65       NA       65
    

    【讨论】:

      【解决方案2】:

      你可以试试下面的代码

      df[-(1:2)] <- t(apply(df, 1, function(v) replace(v, !is.na(v), v["risk"])))[, -(1:2)]
      

      给了

      > df
        id risk speciesA speciesB speciesC speciesD speciesE speciesF
      1  A   40     <NA>     <NA>       40     <NA>     <NA>       40
      2  B   12     <NA>       12     <NA>     <NA>       12     <NA>
      3  C   65     <NA>     <NA>     <NA>       65     <NA>       65
      

      数据

      > dput(df)
      structure(list(id = c("A", "B", "C"), risk = c(40L, 12L, 65L),
          speciesA = c(NA, NA, NA), speciesB = c(NA, "text3", NA),
          speciesC = c("text1", NA, NA), speciesD = c(NA, NA, "text5"
          ), speciesE = c(NA, "text4", NA), speciesF = c("text2", NA,
          "text6")), class = "data.frame", row.names = c(NA, -3L))
      

      【讨论】:

      • 谢谢 - 这似乎依赖于以“文本”开头的文本才能工作,有没有办法用“风险”列中的值替换出现的任何文本行?
      • 刚刚试了一下,效果很好,谢谢!
      【解决方案3】:

      这是一种可能的解决方案:

      df[] <- lapply(df, function(x) ifelse(grepl("text", x), df$risk, x))
      df <- type.convert(df)
      
      # id risk speciesA speciesB speciesC speciesD speciesE speciesF
      # A   40       NA       NA       40       NA       NA       40
      # B   12       NA       12       NA       NA       12       NA
      # C   65       NA       NA       NA       65       NA       65
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-31
        • 2020-06-21
        • 2016-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-16
        • 1970-01-01
        相关资源
        最近更新 更多