get value using rowname and column name in R?

Viewed 679

I want to extract a value using rowname and column name.

df
     A       columnName   C 
row Name 1       11       1
row Name 2       22.8     44
row Name 3       111      33.2

i want to get value 11 using rowname and column name. how to extract value 11 from data frame . i tried below code for this but didn't give me results it's either giving me NA or NULL

df[["columnName"]][["row Name 1"]] 

df$columnName[["row Name 1"]] 


df['columnName', 'row Name 1']
4 Answers

It is not a row name attribute, but a column 'A' So, create a logical index with the 'A' column, use that as row index, while specifying the column as the 'columnName'

df[df$A == 'row Name 1', 'columnName']

Using df defined reproducibly in the Note at the end

1) use subset as shown.

subset(df, A == "rowName1")$columnName
## [1] 11

2) Another possibility assuming that the row names are unique is to make them real row names removing the column that contains them. Then just use ordinary subscripting.

library(tibble)

df2 <- column_to_rownames(df, "A")
df2["rowName1", "columnName"]
## [1] 11

Note

Lines <- "
     A       columnName   C 
rowName1       11       1
rowName2       22.8     44
rowName3       111      33.2"
df <- read.table(text = Lines, header = TRUE)

You can try subset like below

subset(df, subset = A == "row Name 1", select = columnName)

If you assign column A as your row names, then you can search using the indexing.

> row.names(df) <- df$A
> df$A <- NULL

> df
           columnName    C
row Name 1       11.0  1.0
row Name 2       22.8 44.0
row Name 3      111.0 33.2

> df["row Name 1", "columnName"]
[1] 11
Related