Home > Enterprise >  Extract Row and Column Name if the value for the cell in the data frame is greater than 0 and save v
Extract Row and Column Name if the value for the cell in the data frame is greater than 0 and save v

Time:06-09

I have a data frame:
--X Y Z

A 1 2 3

B 0 0 1

C 0 1 0

I want to extract row and column name of the cell from the data frame where the value of that cell is greater than 0 and store the value, row and column name to another data frame which I created and is empty.

mP3 <- data.frame()

I tried :mp3<- which(rownames(df[,] > 0))

but it has not worked. Any help is appreciated

CodePudding user response:

Just use which(, arr.ind=TRUE):

mP3 <- structure(list(X = c(1, 0, 0), Y = c(2, 0, 1), Z = c(3, 1, 0)), 
    class = "data.frame", row.names = c("A", "B", "C"))
mP3
#   X Y Z
# 1 1 2 3
# 2 0 0 1
# 3 0 1 0
idx <- which(mP3 > 0, arr.ind=TRUE)
results <- data.frame(Row=rownames(mP3)[idx[, 1]], Col=colnames(mP3)[idx[, 2]], Val=mP3[idx])
results
#   Row Col Val
# 1   A   X   1
# 2   A   Y   2
# 3   C   Y   1
# 4   A   Z   3
# 5   B   Z   1

CodePudding user response:

Try this

df <- data.frame(X = c(1,0,0) , Y = c(2,0,1) , Z = c(3,1,0))
rownames(df) <- c("A" , "B" , "C")

#===================================
ans <- matrix(NA , sum(df > 0) , 3)
r <- 1L
for(i in 1:nrow(df)){
  for(j in 1:ncol(df)){
    if(df[i,j] > 0 ){
      ans[r,1] <- df[i,j] 
      ans[r,2] <- rownames(df)[i]
      ans[r,3] <- colnames(df)[j]
      r <- r   1L
    } 
  }
}
#===================================

colnames(ans) <- c("Value" , "R_name" , "C_name")
ans
#>      Value R_name C_name
#> [1,] "1"   "A"    "X"   
#> [2,] "2"   "A"    "Y"   
#> [3,] "3"   "A"    "Z"   
#> [4,] "1"   "B"    "Z"   
#> [5,] "1"   "C"    "Y"

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

CodePudding user response:

The code below might help.

df <- data.frame(X=c(1,0,0),Y= c(2,0,0),Z=c(3,1,0))
rownames(df) <-  c("A","B","C")
df2 <- data.frame(matrix(ncol=dim(df)[2],nrow=dim(df)[1]))
for(i in 1:dim(df)[1]){
  for(j in 1:dim(df)[2]){
    if(df[i,j]>0)
      df2[i,j] <- paste0(rownames(df)[i],"-",colnames(df)[j])
    else
      df2[i,j] <- 0
    
  }
}
df2
  •  Tags:  
  • r
  • Related