【问题标题】:Insert value into dataframe easily in R在 R 中轻松将值插入数据框
【发布时间】:2022-01-20 03:42:39
【问题描述】:

考虑以下data.frame:

df <- data.frame(Industry = c("Agriculture", "Fishery", "Industry"),
                 Value    = c(0,0,0))

我想轻松地将值放入数据框中。假设我想要“农业”的数字 1。当然,在这种情况下,我可以通过以下方式轻松做到:

df <- data.frame(Industry = c("Agriculture", "Fishery", "Industry"),
                 Value    = c(1,0,0))

但是我有一个巨大的数据框,所以这并不容易。相反,我可以写:

change <- c("Agriculture", 1)

然后如果是macthing,那么它会更新df。但是我该怎么做呢?我应该可以同时更改多个单元格(例如,“农业”和“渔业”)。

【问题讨论】:

    标签: r matching


    【解决方案1】:

    使用data.table 方法使用合并和就地更新

    library(data.table)
    
    # set df as dt
    dt <- data.table(df)
    
    # update table
    updt <- fread(text="
      Industry,New_Value
      Agriculture,1
      Fishery,2
    ")
    
    # temporary merge on Industry column to fetch new value
    # and inplace update dt
    dt[
      updt, on="Industry", # merging
      Value := New_Value # inplace update
    ]
    
    

    得到

          Industry Value
    1: Agriculture     1
    2:     Fishery     2
    3:    Industry     0
    

    【讨论】:

      【解决方案2】:

      你可以试试

      df$Value[df$Industry == "Agriculture"] <- 1
      
           Industry Value
      1 Agriculture     1
      2     Fishery     0
      3    Industry     0
      

      df$Value[df$Industry %in% c("Agriculture", "Fishery")] <- 1
           Industry Value
      1 Agriculture     1
      2     Fishery     1
      3    Industry     0
      

      【讨论】:

        【解决方案3】:

        dplyr 解决方案:

        您可以写下要更新的行业列表,然后在 mutate 函数中使用 %in% 运算符:

        library(dplyr)
        
        df <- data.frame(Industry = c("Agriculture", "Fishery", "Industry"),
                         Value    = c(0,0,0))
        
        list_of_industries <- c("Agriculture","Fishery")
        
        df <- df %>% 
          mutate(Value = ifelse(Industry %in% list_of_industries,
                                1,
                                0))
        

        输出:

             Industry Value
        1 Agriculture     1
        2     Fishery     1
        3    Industry     0
        

        【讨论】:

        • 谢谢!但是,如果我想将“农业”更改为 1,将“渔业”更改为 2,我该怎么做? :-)
        • @Michael 你可以使用case_when 语句:mutate(Value = case_when(Industry == "Agriculture" ~ 1, Industry == "Fishery" ~ 2, TRUE ~ 0))
        猜你喜欢
        • 2018-04-16
        • 2020-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-17
        • 2011-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多