我这里有这个代码:
test = test %>% left_join(dischargestatuscode, by = "DischargeStatusID") %>% select(-DischargeStatusID) %>% select(-Code)
test = test %>% left_join(statecode, by = "StateID") %>% select(-StateID) %>% select(-Code)
test = test %>% left_join(gendercode, by = "GenderID") %>% select(-GenderID) %>% select(-Code) %>% select(-Gender.1ID)
test = test %>% left_join(racecode, by = "RaceID") %>% select(-RaceID) %>% select(-Code)
test = test %>% left_join(agecode, by = "AgeID") %>% select(-AgeID) %>% select(-Code) %>% select(-(MinAge:MaxAge))
test = test %>% left_join(icd9codes, by = "ICDAccessCodeID") %>% select(-ICDAccessCodeID) %>% select(-(ICD9Code:CodeType))
%>% select(-LongDescription)
test = test %>% left_join(diagnosistypecode, by = "DiagnosisCodeTypeID") %>% select(-DiagnosisCodeTypeID) %>% select(-Code)
test = test %>% left_join(hcpcscode, by = "HCPCCodeID") %>% select(-HCPCCodeID) %>% select(-Code)
test = test %>% left_join(countycode, by = "CountyID") %>% select(-CountyID) %>% select(-Code)
我只是想知道是否有更简单的方式来写这个。我在想也许是for循环或者也许是lapply?非常感谢您的帮助!
我认为可能有用的代码:
for (i in seq(CodeList)) {
test %>% left_join(i, by = i[1])
}
答案 0 :(得分:0)
由于始终有left_join
包含数据和参数,后跟带有一个参数的select,因此这些操作可以包含在函数中。只有需要谨慎的是论据评价。这由quote
和eval
处理,并且可以与其他输入一起使用。
注意:这只会使您的代码水平缩短
> set.seed(4) # toy data generation
> dat <- data.frame(id = 1:4, char = letters[sample(1:4)])
> dat2 <- data.frame(id = 1:4, char = letters[sample(1:4)])
> library(dplyr)
> f <- function(y1, by1, s2)
dat %>% left_join(y1, by = by1) %>% select(eval(s2))
# example usage
> f(dat2, 'id', quote(-id))
char.x char.y
1 c d
2 a a
3 d b
4 b c
> f(dat2, 'id', quote(id:char.x))
id char.x
1 1 c
2 2 a
3 3 d
4 4 b
这些可以很容易地扩展到两个选择操作,第三个是可选的。