我有以下代码,并且通常使用ifelse在我的data.frame中创建一个包含我重命名值的列,但这次我的嵌套值数> 50,所以有人对我可以使用的其他内容有任何想法根据另一个值创建一个新列? 我事件尝试将它们拆分为3个新列,然后将这些新列组合在一起,但不断出现错误。
df$ARV <- transform(df$ADAV1 == "055", "Isoprinosine",
ifelse(df$ADAV1 == "056", "HPA-23",
ifelse(df$ADAV1 == "057", "Suramin",
ifelse(df$ADAV1 == "058", "Ribavirin",
ifelse(df$ADAV1 == "090", "Alpha Interferon",
ifelse(df$ADAV1 == "091", "Foscarnet/PFA",
ifelse(df$ADAV1 == "092", "AZT",
ifelse(df$ADAV1 == "094", "ddC",
ifelse(df$ADAV1 == "098", "AL-721",
ifelse(df$ADAV1 == "101", "Ampligen",
ifelse(df$ADAV1 == "108", "Peptide T",
ifelse(df$ADAV1 == "110", "Dextran-Sulfate",
ifelse(df$ADAV1 == "122", "Beta Interferon",
ifelse(df$ADAV1 == "128", "CD4",
ifelse(df$ADAV1 == "147", "ddI",
ifelse(df$ADAV1 == "159", "d4T",
ifelse(df$ADAV1 == "163", "ddA",
ifelse(df$ADAV1 == "179", "adenosine arabinoside",
ifelse(df$ADAV1 == "180", "AZT/ddI Blinded Trial",
ifelse(df$ADAV1 == "185", "AZT/ddC Blinded Trial",
ifelse(df$ADAV1 == "186", "ddI/ddC Blinded Trial",
ifelse(df$ADAV1 == "187", "AZT/ddI/ddC Blinded Trial",
ifelse(df$ADAV1 == "191", "Nevirapine",
ifelse(df$ADAV1 == "192", "TAT inhibitors",
ifelse(df$ADAV1 == "193", "PI-O",
ifelse(df$ADAV1 == "194", "U-90/152/Delavirdine",
ifelse(df$ADAV1 == "201", "AZT/d4T Trial",
ifelse(df$ADAV1 == "204", "3TC",
ifelse(df$ADAV1 == "205", "AZT/3-TC Blinded Trial",
ifelse(df$ADAV1 == "206", "AZT/ddI/PI Blinded Trial",
NA )))))))))))))))))))))))))))))))
df$ARV2 <- ifelse(df$ADAV1 == "208", "AZT/PI Blinded Trial",
ifelse(df$ADAV1 == "209", "d4T/PI Blinded Trial",
ifelse(df$ADAV1 == "210", "Saquinavir",
ifelse(df$ADAV1 == "211", "Ritonavir",
ifelse(df$ADAV1 == "212", "Indinavir",
ifelse(df$ADAV1 == "214", "AZT/3-TC/PI Blinded Trial",
ifelse(df$ADAV1 == "216", "Nelfinavir",
ifelse(df$ADAV1 == "217", "ABT-378",
ifelse(df$ADAV1 == "218", "Abacavir",
ifelse(df$ADAV1 == "219", "141W94",
ifelse(df$ADAV1 == "220", "Enfavirenz",
ifelse(df$ADAV1 == "221", "MKC442",
ifelse(df$ADAV1 == "222", "Lobucavir",
ifelse(df$ADAV1 == "223", "Loviride",
ifelse(df$ADAV1 == "224", "Adefovir",
ifelse(df$ADAV1 == "227", "Combivir",
ifelse(df$ADAV1 == "231", "Vistide",
ifelse(df$ADAV1 == "233", "T-20",
ifelse(df$ADAV1 == "234", "PMPA",
ifelse(df$ADAV1 == "238", "Timpranavir",
ifelse(df$ADAV1 == "239", "Emtricitabine",
ifelse(df$ADAV1 == "998", "Other",
NA ))))))))))))))))))))))
答案 0 :(得分:3)
最简单的选择是创建一个key / val data.frame,然后执行left_join
library(dplyr)
keyval <- data.frame(ADAV1 = c("055", "056", ...),
val = c("Isoprinosine","HPA-23", ...), stringsAsFactors = FALSE)
left_join(df, keyval) %>%
mutate(ARV = replace(ADAV1, is.na(ADAV1), val))
同样,如果有另一组key / val用于生成&#39; ARV2&#39;,则创建
keyval2 <- data.frame(ADAV1 = c("208", "209", ...),
val = c( "AZT/PI Blinded Trial", "d4T/PI Blinded Trial", ...),
stringsAsFactors = FALSE)
并进行第二次加入
或者将它们放在list
中,然后使用map
library(purrr)
list(keyval, keyval2) %>%
map2_df(., c("ARV", "ARV2"), ~ left_join(df, .x) %>%
transmute(!! (.y) := replace(ADAV1, is.na(ADAV1), val))) %>%
bind_cols(df, .)