Home > Enterprise >  Add and replicate a new column for each group in R
Add and replicate a new column for each group in R

Time:07-12

I have a data frame like this

df <- data.frame(id = c(12345,12345,12345,221,221,221),
                 range_key = c('2022 Q2','2022 Q3','2023 Q4','2022 Q2','2023 Q3','2023 Q4'), week = c(w 1,w 1,w 2,w 3,w 3, w 4))

I want to add another column which is

country_list <-  c('US','CA','JP','KR','NZ','AU','PH','ID','TH','IN','MX','CO','CL','AR','BR','DE','IT','GB','ES','FR','NL') %>% data.frame(country=.)

to the data frame I tried the following method but it does not work for big data set

for(i in 1:length(country_list$country)){
  temp_data <- (df) %>% mutate(country= country_list$country[i])
  all_data <- rbind.fill(temp_data, df)
  #rm(temp_data)
  }

CodePudding user response:

I need to define a new empty data frame and then append to this new data frame

new_df <- data.frame()
for(i in 1:length(country_list$country)){
  temp_data <- (df) %>% mutate(country= country_list$country[i])
  new_df <- rbind.fill(temp_data, new_df)
  #rm(temp_data)
  }

CodePudding user response:

Is it no enough with cbind()? Maybe I'm missing something here... I mean:

df1 <- cbind(df, country_list)

CodePudding user response:

But if you want to run some sort of loop you could use something like this:

df1 <- apply(df, 1, function(x) {cbind(?})
  • Related