Home > Software engineering >  Insert value into dataframe easily in R
Insert value into dataframe easily in R

Time:12-17

Consider the following data.frame:

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

I want to easily put a value into the dataframe. Let's say I want the number 1 for "Agriculture". Of course, in this case I could easily do it by:

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

But I have a huge dataframe, so it is not that easy to do. Instead is it possible that I could write:

change <- c("Agriculture", 1)

And then if it is macthing, then it will update df. But how do I do that? It should be possible for me to change multiple cells (for instance, both "Agriculture" and "Fishery") at the same time.

CodePudding user response:

A dplyr solution:

You could write down a list of the industries you want to update, then use %in% operator inside a mutate function:

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))

Output:

     Industry Value
1 Agriculture     1
2     Fishery     1
3    Industry     0

CodePudding user response:

You may try

df$Value[df$Industry == "Agriculture"] <- 1

     Industry Value
1 Agriculture     1
2     Fishery     0
3    Industry     0

and

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

CodePudding user response:

Using a merge and inplace update using data.table approach

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
]

Got

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