Reputation: 177
This is the code to implement my data frame:
breast <- read.table("breastdata.txt", header=T, sep=" ", fill=TRUE)
Now I want like to replace the first column, that contains factor M and B, to the factor -1 and +1. So when it is "M" then I would replace it by +1. I've got the next code but it doesn't work:
for(i in 1:569)
{
if(breast[i,1]=="M")
{
breast[i,1] <- as.factor(-1)
}
else{
breast[i,1] <- as.factor(1)
}
}
Could someone help me?
Upvotes: 1
Views: 243
Reputation: 1585
breast$first_column[breast$first_column=="B"] <- "1"
breast$first_column[breast$first_column=="M"] <- "-1"
Upvotes: 2
Reputation: 13076
Assuming that levels(breast[,1]) == c("B", "M")
, just call:
levels(breast[,1]) <- c("1", "-1")
This will only change the factor's labels, without changing its internal representation. Thus, it is a very fast operation.
Upvotes: 2