我正在尝试从我的数据中的详细类别中创建一个广泛的行业类别。我想知道在R中用grepl创建这个是哪里错了?
我的示例数据如下:
df <- data.frame(county = c(01001, 01002, 02003, 04004, 08005, 01002, 02003, 04004),
ind = c("0700","0701","0780","0980","1000","1429","0840","1500"))我正在尝试在R中使用grepl或str_replace命令创建两个级别(例如,农业、制造)的名为行业的变量。
我已经尝试过了:
newdf$industry <- ""
newdf[df$ind %>% grepl(c("^07|^08|^09", levels(df$ind), value = TRUE)), "industry"] <- "Agri"但这会给出以下错误:
argument 'pattern' has length > 1 and only the first element will be used我希望获得以下数据帧作为我的结果:
newdf <- data.frame(county = c(01001, 01002, 02003, 04004, 08005, 01002, 02003, 04004),
ind = c("0700","0701","0780","0980","1000","1429","0840","1500"),
industry = c("Agri", "Agri", "Agri", "Agri", "Manufacturing", "Manufacturing", "Agri", "Manufacturing"))所以我的问题是,如果变量'ind‘以07,08或09开头,我的行业变量将取值'agri',如果'ind’以10,14或15开头,如何指定行业将是‘制造业’?不用说,我正在尝试处理10个类别的大量行业代码,因此正在寻找一个解决方案,以帮助我在模式识别方面做到这一点。
如有任何帮助,我们不胜感激!谢谢!
发布于 2019-04-09 02:36:25
试试这个:
newdf = df %>%
mutate(industry = ifelse(str_detect(string = ind,
pattern = '^07|^08|^09'),
'Agri',
'Manufacturing'))发布于 2019-04-09 02:44:22
这是可行的,使用ifelse()向df data.frame添加所需的列
df$industry <- ifelse(grepl(paste0("^", c('07','08','09'), collapse = "|"), df$ind), "Agri", "Manufacturing")
> df
county ind industry
1 1001 0700 Agri
2 1002 0701 Agri
3 2003 0780 Agri
4 4004 0980 Agri
5 8005 1000 Manufacturing
6 1002 1429 Manufacturing
7 2003 0840 Agri
8 4004 1500 Manufacturinghttps://stackoverflow.com/questions/55579609
复制相似问题