Reputation: 125
I have to check if a value in two columns or lists has the same class. I wrote the following codes but none are working because just write the last value on the list but not only the first values.
x <- c(1,3,6,2) ## All are numeric
y <- c(6,4,3,'a') ## Note that is a string at here
m <- NULL
for (i in length(x)) {
if (class(x[i]) == class(y[i])) m[i] <-'ok' else m[i] <- 'no ok'
}
et <-function(x, y){
for (i in length(x)) {
if (class(x[i]) == class(y[i])) {
m[i] = 'ok'
} else {
m[i] = 'not ok'
}
return(f)
}
}
et(x,y)
Thanks for helping.
Upvotes: 0
Views: 370
Reputation: 886998
We can also loop through using lapply/sapply
and get a logical output
sapply(seq_along(x), function(i) class(x[[i]])==class(y[[i]]))
x <- list(1,3,6,2)
y <- list(6,4,3,'a')
Upvotes: 0
Reputation: 214917
If you want to check the class of corresponding elements in two lists, you can use Map
function:
x <- list(1,3,6,2)
y <- list(6,4,3,'a')
Map(function(x,y) c("no ok", "ok")[as.integer(class(x) == class(y)) + 1], x, y)
[[1]]
[1] "ok"
[[2]]
[1] "ok"
[[3]]
[1] "ok"
[[4]]
[1] "no ok"
Or mapply
which returns a vector:
mapply(function(x,y) c("no ok", "ok")[as.integer(class(x) == class(y)) + 1], x, y)
[1] "ok" "ok" "ok" "no ok"
Upvotes: 2
Reputation: 5580
Your problem is in the for loop call, which is only passing one integer to run, rather than a list of integers, like you're hoping. Change this:
for (i in length(x)) { ...
to this:
for (i in 1:length(x)) { ...
Notice that "length(x)" is 4, whereas "1:length(x)" is all integers 1:4.
Upvotes: 3