简体   繁体   中英

r - Select DF based on value in column of another DF

I want to bind the columns of 2 dataframes. The second dataframe should be choosen among several dataframes in my environment, depending on the value of a cell in the first dataframe.

Sample Data

test <- structure(list(main_activity = structure(c(1L, 9L), .Label = c("Manufacturing", 
"Manufacturing; Retail", "Manufacturing; Services", "Manufacturing; Wholesale", 
"Manufacturing; Wholesale; Services", "Retail", "Retail; Services", 
"Retail; Wholesale", "Services", "Services; Manufacturing", "Services; Retail", 
"Services; Wholesale", "Wholesale", "Wholesale; Manufacturing", 
"Wholesale; Retail", "Wholesale; Services"), class = "factor"), 
    p_l_for_period_net_income_th_eur_2019 = c(-4849.968, -4416.404
    ), Name = c("A", "B")), class = "data.frame", row.names = c(NA, 
-2L))

Manufacturing_2015 <- as.data.frame(matrix(data = c(2000)))
Services_2015 <- as.data.frame(matrix(data = c(3000)))

What I want to be able to do is to check the value of the column 'main_activity' and bind the dataframe that matches that name with the 'test' dataframe. So, the goal is to have the following:

Desired Outcome

binded_A <- cbind(test %>% filter(Name == "A"), Manufacturing_2015)
binded_B <- cbind(test %>% filter(Name == "B"), Services_2015)

Is there a way to do it automatically?

You can use ls to select a data frame from the global environment based on it's value in main_activity and cbind the data to original subset of dataframe.

result <- lapply(test$main_activity, function(x) cbind(subset(test, 
               main_activity == x), get(ls(pattern = x, envir = .GlobalEnv))))

result

#[[1]]
#  main_activity p_l_for_period_net_income_th_eur_2019 Name   V1
#1 Manufacturing                             -4849.968    A 2000

#[[2]]
#  main_activity p_l_for_period_net_income_th_eur_2019 Name   V1
#2      Services                             -4416.404    B 3000

This will return you a list of dataframes, if you need them as separate dataframes name them and use list2env .

names(result) <- paste0('binded_', test$Name)
list2env(result, .GlobalEnv)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM