I try to program a script in R, which should go through a dataframe looking for columns with formal/nominal entries. Finding such a column it should extract all entered values in a vector and add for each of those a column with binary data(0,1).
Problem: sign names to column with a variable data$lev[z] <- data[,x]==lev[z]
is not working. lev[]
is a vector with names, z
is an index for a loop.
Would be great if someone could help me out.
Thanks in advance. Cheers
I believe your only issue is that your last line should have sample[,lev[z]]
rather than sample$lev[z]
. As you currently have it (ie sample$lev[z]
) you are telling R to assign a vector (TRUE, FALSE, FALSE)
to the lev
column of sample
in row z
. In this example, you are trying to put 3 things into one place. Hence your warning message: number of items to replace is not a multiple of replacement length
.
A working code would be:
letter <- c("a","b","c")
id <- c(1,2,3)
sample <- data.frame(id,letter)
y <- NCOL(sample)
x <- 0
while ( x < y){
x <- x+1
test01 <- is.factor(sample[,x])
if(test01 == TRUE ){
lev <- levels(sample[,x])
q <- length(lev)
z <- 0
while (z < q){
z <- z+1
sample[,lev[z]] <- sample[,x]==lev[z]
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.