我想在我的数据框中检查TRUE,FALSE,TRUE和其他七种组合,这些组合有87027行和三列。我想为每一行写出结果;
TRUE TRUE TRUE -> abc
TRUE TRUE FALSE-> ab
TRUE FALSE TRUE->ac
FALSE TRUE TRUE->bc
和其他人......
以下是简化的示例数据框:
A B C
TRUE FALSE FALSE
TRUE FALSE FALSE
FALSE FALSE FALSE
TRUE FALSE TRUE
FALSE FALSE TRUE
为此我写了一个for循环
for (i in 1:87027) {
if (data$A[i]=="TRUE" & data$B[i]=="TRUE" ) {
if (data$C[i]=="TRUE") {
data$new[i]="abc"
}
}
if (data$A[i]=="TRUE" & data$B[i]=="TRUE" ) {
if (data$C[i]=="FALSE") {
data$new[i]="ab"
}
}
if (data$A[i]=="TRUE" & data$B[i]=="FALSE" ) {
if (data$C[i]=="TRUE") {
data$new[i]="ac"
}
}
if (data$A[i]=="TRUE" & data$B[i]=="FALSE" ) {
if (data$C[i]=="FALSE") {
data$new[i]="a"
}
}
if (data$A[i]=="FALSE" & data$B[i]=="FALSE" ) {
if (data$C[i]=="FALSE") {
data$new[i]="Nothing"
}
}
if (data$A[i]=="FALSE" & data$B[i]=="TRUE" ) {
if (data$C[i]=="TRUE") {
data$new[i]="bc"
}
}
if (data$A[i]=="FALSE" & data$B[i]=="TRUE" ) {
if (data$C[i]=="FALSE") {
data$new[i]="b"
}
}
if (data$A[i]=="FALSE" & data$B[i]=="FALSE" ) {
if (data$C[i]=="TRUE") {
data$new[i]="c"
}
}
}
运行此代码需要几分钟,我想知道如何以复杂的方式执行此操作
答案 0 :(得分:2)
# Make some sample data (you should do this next time...)
n <- 87027
col <- 3
mat <- matrix(sample(c(T,F), n*col, rep=T), n, col)
# Function that does the conversion you want
# It takes in x which is assumed to be a vector of three logical
# values
f <- function(x){
if(all(!x)){
return("Nothing")
}
out <- paste(letters[1:3][x], collapse = "")
return(out)
}
# Use f on every row of mat
output <- apply(mat, 1, f)
产生
> head(mat)
[,1] [,2] [,3]
[1,] TRUE FALSE FALSE
[2,] FALSE TRUE FALSE
[3,] FALSE FALSE FALSE
[4,] TRUE FALSE TRUE
[5,] FALSE TRUE FALSE
[6,] TRUE FALSE FALSE
> head(output)
[1] "a" "b" "Nothing" "ac" "b" "a"
花了很少的时间跑。