如何从私有数据创建示例数据集(用不提供信息的占位符替换变量名称和级别)?

为了提供方法的可重现示例,必须经常提供数据集。我不想建立示例数据集,而是希望使用自己的一些数据。但是,此数据无法发布。我希望用不具信息性的占位符(例如V1 .... V5,L1 .... L5)替换变量(列)名称和因子级别。

有自动的方法可以做到这一点吗?

理想情况下,这将在R中完成,接受一个data.frame并生成此匿名data.frame。

有了这样的数据集,只需在脚本中搜索并替换变量名,您便拥有了一个可公开发布的可复制示例。

这样的过程可能会增加在可复制示例中包含适当数据,甚至在问题,评论和错误报告中还会包含可复制示例。


慕哥6287543
浏览 427回答 3
3回答

PIPIONE

我不知道是否有被自动执行此功能,但现在没有;)## A function to anonymise columns in 'colIDs'&nbsp;##&nbsp; &nbsp; colIDs can be either column names or integer indicesanonymiseColumns <- function(df, colIDs) {&nbsp; &nbsp; id <- if(is.character(colIDs)) match(colIDs, names(df)) else colIDs&nbsp; &nbsp; for(id in colIDs) {&nbsp; &nbsp; &nbsp; &nbsp; prefix <- sample(LETTERS, 1)&nbsp; &nbsp; &nbsp; &nbsp; suffix <- as.character(as.numeric(as.factor(df[[id]])))&nbsp; &nbsp; &nbsp; &nbsp; df[[id]] <- paste(prefix, suffix, sep="")&nbsp; &nbsp; }&nbsp; &nbsp; names(df)[id] <- paste("V", id, sep="")&nbsp; &nbsp; df}## A data.frame containing sensitive informationdf <- data.frame(&nbsp; &nbsp; name = rep(readLines(file.path(R.home("doc"), "AUTHORS"))[9:13], each=2),&nbsp; &nbsp; hiscore = runif(10, 99, 100),&nbsp; &nbsp; passwd = replicate(10, paste(sample(c(LETTERS, letters), 9), collapse="")))## Anonymise itdf2 <- anonymiseColumns(df, c(1,3))## Check that it worked> head(df, 3)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;name&nbsp; hiscore&nbsp; &nbsp; passwd1 Douglas Bates 99.96714 ROELIAncz2 Douglas Bates 99.07243 gDOLNMyVe3 John Chambers 99.55322 xIVPHDuEW&nbsp; &nbsp;&nbsp;> head(df2, 3)&nbsp; name hiscore&nbsp; V31&nbsp; &nbsp;Q1 99.96714 V82&nbsp; &nbsp;Q1 99.07243 V23&nbsp; &nbsp;Q2 99.55322 V9
打开App,查看更多内容
随时随地看视频慕课网APP