我试图从我的数据中的详细类别创建一个广泛的行业类别。我想知道在使用gre中的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命令的帮助下创建一个名为industry的变量,其中包含2个级别(例如,agri,制造)。
我试过这个:
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个类别中处理,所以寻找一个可以帮助我做模式识别的解决方案。
任何帮助表示赞赏!谢谢!
试试这个:
newdf = df %>%
mutate(industry = ifelse(str_detect(string = ind,
pattern = '^07|^08|^09'),
'Agri',
'Manufacturing'))
这可行,使用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 Manufacturing