Home > Back-end >  how to fill in certain values where rowname and column name are identical
how to fill in certain values where rowname and column name are identical

Time:08-15

Suppose I have a data frame as follows:

dat <- data.frame(
  ee=1:4,
  bb = 4:7,
  cc =4:7,
  dd = 2:5
)  
rownames(dat) <- colnames(dat)
dat
   ee bb cc dd
ee  1  4  4  2
bb  2  5  5  3
cc  3  6  6  4
dd  4  7  7  5

How can I replace the cell value to 1 where column and row names are the same? also suppose that the position may not in the diagonal the position needing replacement can occur in an arbitrary position.

CodePudding user response:

This surprisingly works for a data frame:

diag(dat) <- 1

But guess what, diag(dat) does not work.

CodePudding user response:

To answer the general question 'How can I replace the cell value where column and row names are the same?' for arbitrary column positions use match() (I replaced by 9 to make the point)

library(tibble)
dat <- data.frame(
  ee = 1:4,
  bb = 4:7,
  cc = 4:7,
  dd = 2:5
)  
set.seed(1157)
rownames(dat) <- sample(colnames(dat))
dat
#>    ee bb cc dd
#> dd  1  4  4  2
#> ee  2  5  5  3
#> cc  3  6  6  4
#> bb  4  7  7  5


replace_index <- tibble(
  row    = 1:nrow(dat), 
  column = match(rownames(dat), colnames(dat))
)
replace_index
#> # A tibble: 4 × 2
#>     row column
#>   <int>  <int>
#> 1     1      4
#> 2     2      1
#> 3     3      3
#> 4     4      2

dat[as.matrix(replace_index)] <- 9
dat
#>    ee bb cc dd
#> dd  1  4  4  9
#> ee  9  5  5  3
#> cc  3  6  9  4
#> bb  4  9  7  5

Created on 2022-08-15 by the reprex package (v2.0.1)

CodePudding user response:

Identify the common names and assign the value. Try this:

imhere <- rownames(dat)[rownames(dat) %in% colnames(dat)]

for (i in imhere) dat[i,i] <- 999
  • Related