R:构建条件组合
我正在寻找一种有效的方法来构建具有大量条件组合的数据帧。我试图将这个过程转化为某种“创建df”灵活的功能,其工作原理如下:R:构建条件组合,r,R,我正在寻找一种有效的方法来构建具有大量条件组合的数据帧。我试图将这个过程转化为某种“创建df”灵活的功能,其工作原理如下: # STEP 1 level.1 <- c("Netherlands", "New Zealand", "Europe") # STEP 2: level.1 <- c("Netherlands", "New Zealand", "Europe", "Europe") level.2 <- c(NA, NA, "London", "Paris") df
# STEP 1
level.1 <- c("Netherlands", "New Zealand", "Europe")
# STEP 2:
level.1 <- c("Netherlands", "New Zealand", "Europe", "Europe")
level.2 <- c(NA, NA, "London", "Paris")
df <- data.frame(level.1, level.2)
df
# STEP 3:
level.1 <- c("Netherlands", "New Zealand", "Europe", "Europe", "Europe", "Europe")
level.2 <- c(NA, NA, "London", "London", "Paris", "Paris")
level.3 <- c(NA, NA, "City", "Roads", "City", "Roads")
data.frame(level.1, level.2, level.3)
# STEP 4:
level.1 <- c("Netherlands", "New Zealand", "Europe", "Europe", "Europe", "Europe", "Europe", "Europe")
level.2 <- c(NA, NA, "London", "London", "London", "London", "Paris", "Paris")
level.3 <- c(NA, NA, "City", "City", "Roads", "Roads", "City", "Roads")
level.4 <- c(NA, NA, "A-Regulated", "G-Regulated", "A-Regulated", "G-Regulated", NA, NA)
data.frame(level.1, level.2, level.3, level.4)
#步骤1
level.1您可以通过使用merge来实现这一点,并将其简化为循环
在每个级别,您将只需要指定要加入的值:
level.1 <- data.frame(country = c("Netherlands", "New Zealand", "Europe"))
level.2 <- data.frame(country = c("Europe"), city = c('paris','london' ))
level.3 <- data.frame(country = c('Europe'), location = c('city', 'roads'))
level.4 <- data.frame(country = c('Europe'), regulation = c("A-Regulated", "G-Regulated", "C-Regulated"))
level.1 <- data.frame(country = c("Netherlands", "New Zealand", "Europe"))
level.2 <- data.frame(country = c("Europe"), city = c('paris','london' ))
level.3 <- data.frame(country = c('Europe'), location = c('city', 'roads'))
level.4 <- data.frame(country = c('Europe'), regulation = c("A-Regulated", "G-Regulated", "C-Regulated"))
Reduce(function(x, y) merge(x, y, all=TRUE), list(level.1, level.2, level.3, level.4))
country city location regulation
1 Europe paris city A-Regulated
2 Europe paris city G-Regulated
3 Europe paris city C-Regulated
4 Europe paris roads A-Regulated
5 Europe paris roads G-Regulated
6 Europe paris roads C-Regulated
7 Europe london city A-Regulated
8 Europe london city G-Regulated
9 Europe london city C-Regulated
10 Europe london roads A-Regulated
11 Europe london roads G-Regulated
12 Europe london roads C-Regulated
13 Netherlands <NA> <NA> <NA>
14 New Zealand <NA> <NA> <NA>
merge(merge(merge(level.1, level.2, all = TRUE), level.3, all = TRUE), level.4, all = TRUE)