I wanted would like to check whether in each column of a matrix the values are the same as in the first column:
x1 <- c("x", "y", "x")
x2 <- c("x", "y", "y")
x3 <- c("y", "y","x")
dat <- data.frame(x1,x2,x3)
x1 x2 x3
1 x x y
2 y y y
3 x y x
So if x2 != 2, there should be a "1", otherwise a NA. How can I do that? The result in this case would be:
x2 x3
NA 1
NA NA
1 NA
My (not working) solution was:
fun <- function (x) {
for(j in 2: ncol(x)){
ifelse(x[,1]== j, NA,1)
}
}
fun(dat)
I would need a function to perform this with lapply. How can I do that? Thanks a lot!
Different approach using the fact that column-operations are often easy because of argument recycling:
dat <- data.frame(x1,x2,x3, stringsAsFactors=FALSE) # keeps as character
ne.dat1 <- (dat != dat[,1])[ , -1] # True/False rather than 1,NA
is.na(ne.dat1) <- !ne.dat1
ne.dat1
x2 x3
[1,] NA TRUE
[2,] NA NA
[3,] TRUE NA
You could do:
m1 <- (!(as.character(dat[,1])==dat[,-1])) +1
m1[] <- c(NA,1)[m1]
m1
# x2 x3
#[1,] NA 1
#[2,] NA NA
#[3,] 1 NA
This is easier with the wrapper sapply
as it applies applies the names to the result:
sapply(dat[-1],
function(x)
ifelse(as.character(x)==as.character(dat[[1]]), NA, 1)
)
## x2 x3
## [1,] NA 1
## [2,] NA NA
## [3,] 1 NA
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.