只是想知道为什么此代码不起作用?我对如何在if语句中使用colnames感兴趣。
mat <- matrix(, nrow = 3, ncol = 3)
row.names(mat) <- c("nc","sc","ny")
col.names(mat) <- c("BMW","Toyota","Honda")
for(row in 1:nrow(mat)) {
for(col in 1:ncol(mat)) {
if(colnames(mat1)[1] == "nc"){
mat[row,col]=0
}
else {mat[row,col]=12}
}
}
感谢吨!
答案 0 :(得分:1)
代码中的问题是:
row.names
应该是colnames
col.names
应该是rownames
mat1
应该是mat
colnames(mat)[1] == "nc"
始终为TRUE或始终为FALSE,这取决于mat
是什么。大概您想要colnames(mat)[col] == "nc"
将所有这些放在一起,我们得到:
mat <- matrix(, nrow = 3, ncol = 3)
rownames(mat) <- c("BMW", "Toyota", "Honda")
colnames(mat) <- c("nc", "sc", "ny")
for(row in 1:nrow(mat)) {
for(col in 1:ncol(mat)) {
if(colnames(mat)[col] == "nc") {
mat[row, col] <- 0
} else {
mat[row,col] <- 12
}
}
}
mat
## nc sc ny
## BMW 0 12 12
## Toyota 0 12 12
## Honda 0 12 12
还请注意,if
可以简化为:
mat[row, col] <- if (colnames(mat)[col] == "nc") 0 else 12
1)完全矢量化的替代方式:可以用矢量化(即无循环)的方式进行替代:
mat2 <- matrix(12, nrow = 3, ncol = 3,
dimnames = list(c("BMW", "Toyota", "Honda"), c("nc", "sc", "ny")))
mat2[, "nc"] <- 0
identical(mat, mat2)
## [1] TRUE
2)另一种完全矢量化的替代方法,我们可以使用以下cbind
。它只需要一行代码。
mat3 <- cbind(nc = c(BMW = 0, Toyota = 0, Honda = 0), sc = 12, ny = 12)
identical(mat, mat3)
## [1] TRUE