Reputation: 29
Create a factor vector using 10 random numbers without decimals. Convert the factor vector to numeric vector. Compare 1st and 2nd vector element wise and store the comparison values ie (True or false) in another vector and display it.
vector1 <- factor(floor((runif(10,min=0,max=101))))
vector2 <- as.numeric(v1)
vector3 <- c()
i <- 1
while(i<= 10)
{
if(vector1[i]==vector2[i])
{
vector3[i] ="TRUE"
} else
if(vector1[i]!=vector2[i])
{
vector3[i] = "FALSE"
}
i <- i+1
}
vector3
TRUE, TRUE ,FALSE.......
Upvotes: 2
Views: 4865
Reputation: 200
Working
v1 <- factor(floor((runif(10,min=0,max=101))))
v2 <- as.numeric(levels(v1))[v1]
v3 <- v1 == v2
print(v3)
Upvotes: 1
Reputation: 3670
The RDocumentation states:
If x is a factor,
as.numeric
will return the underlying numeric (integer) representation, which is often meaningless as it may not correspond to the factor levels, see the ‘Warning’ section in factor.
That warning states:
The interpretation of a factor depends on both the codes and the "levels" attribute. Be careful only to compare factors with the same set of levels (in the same order). In particular, as.numeric applied to a factor is meaningless, and may happen by implicit coercion. To transform a factor f to approximately its original numeric values,
as.numeric(levels(f))[f]
is recommended and slightly more efficient thanas.numeric(as.character(f))
.
Similar warnings and advice are given in this R FAQ on CRAN.
So that's exactly what you should do to convert your factor vector to a numeric one:
vector2 <- as.numeric(levels(vector1))[vector1]
To store the comparison results in another vector, you can just do:
vector3 <- vector1 == vector2
Or if you are required to use a for
loop to compare element-wise:
vector3 <-c()
for (i in 1:length(vector1))
{
vector3[i] <- vector1[i] == vector2[i]
}
You can see and run this code here.
Upvotes: 1