For this situation there is a simpler solution, just use the base::replace
.
df1 <- data.frame(High = c(0.51, 0.92, 0.78),
Low = c(0.43, 0.28, 0.22),
Middle = c(0.22, 0.21, 0.9),
nomes = c("current", "former", "never"))
library(tidyverse)
df2 <- df1 %>%
tibble::column_to_rownames("nomes")
df2
> df2
High Low Middle
current 0.51 0.43 0.22
former 0.92 0.28 0.21
never 0.78 0.22 0.90
df3 <- df2 %>%
base::replace(.<0.75, NA)
df3
> df3
High Low Middle
current NA NA NA
former 0.92 NA NA
never 0.78 NA 0.9
If the for
.
m <- matrix(nrow = nrow(df2), ncol = ncol(df2))
for (j in 1:ncol(m)) {
for (i in 1:nrow(m)) {
x <- ifelse(df2[i, j] < 0.75, NA, df2[i, j])
m[i, j] <- x
}
}
m
> m
[,1] [,2] [,3]
[1,] NA NA NA
[2,] 0.92 NA NA
[3,] 0.78 NA 0.9
df4 <- m %>%
as.data.frame() %>%
dplyr::mutate(nomes = df1$nomes)
colnames(df4) <- colnames(df1)
df4 <- df4 %>%
tibble::column_to_rownames("nomes")
df4
> df4
High Low Middle
current NA NA NA
former 0.92 NA NA
never 0.78 NA 0.9