如何将具有多个数字的列转换为一系列虚拟variables?
我需要将一些数据转换成关系数据库。 在数据库实体中,有一系列21个是/否variables。 在当前的格式中,有一列有一系列数字,用空格分隔,每一列对应于该variables的“是”。
例如,该列可能会读取“3 7 12 20”,对于variables3,7,12和20将对应“是”,对于其他所有对象将为“否”。
我需要将该列转换为虚拟variables格式。 我知道我可以在Excel中使用“文本到列”工具来分隔列中的数字。 但是,就我所知。 我怎么能告诉软件一个数字列对应某个特定列的值?
我希望能在Excel中做到这一点,但也开始熟练使用SQL和Stata。
谢谢!
这是Excel中的一种方法。 如果列A2
的当前数据为A2
, B1:V1
的数字为1至21,则在B2
input以下公式,然后根据需要填入下列公式:
=OR(NOT(ISERROR(FIND(" " & B$1& " ",$A2))),LEFT($A2,LEN(B$1)+1)=TEXT(B$1,"@") & " ",RIGHT($A2,LEN(B$1)+1)=" " & TEXT(B$1,"@"),TRIM($A2)=TEXT(B$1,"@"))
这testing了四个条件之一:
- 我们正在查找的值(即第一行相关列中的值),在任何一边都有空格,可以在列A的单元格中find(
FIND(" " & B$1& " ",$A2)
不是一个错误); 要么 - 我们正在寻找的值加上一个尾部空格(
TEXT(B$1,"@") & " "
)是第一列单元格中的第一个LEFT($A2,LEN(B$1)+1)
) ; 要么 - 我们正在寻找的价值加上领先的空间是A列单元格中最后一件事。
- 我们正在寻找的价值是A列单元格中唯一的东西。
虽然你没有提到它,但我想在R中提供一个解决scheme。假设以下源数据:
# Load the needed package, load the workbook containing the input data and read the sheet library(xlsx) wb <- loadWorkbook(file="currentFormat.xlsx") input <- read.xlsx(file="currentFormat.xlsx", sheetIndex=1, startRow=2, header=FALSE, colIndex=1) # Number of individuals/observations/rows N <- nrow(input) # Prepare output data matrix output <- matrix(0, ncol=21, nrow=N) # Get 'Yes' answers for each i in N true <- apply(X=input, 1,FUN=function(z) {as.numeric(unlist(strsplit(z, fixed = TRUE, split = " "))) } ) # Fill the output matrix for(i in 1:N) { output[i, true[[i]]] <- 1 } # Write output spreadsheet write.xlsx(x = as.data.frame(output), file = "dummyData.xlsx", sheetName = "Output", row.names = TRUE)
代码不是很漂亮,但它确实希望你问(我猜):