[英]R loop matrix comparing whether the first column is the same as the other column
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. 因此,如果x2!= 2,则应为“ 1”,否则为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. 我需要一个函数来用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
,因为它适用于应用名称的结果:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.