简体   繁体   English

使用 R 中的行名和列名获取值?

[英]get value using rowname and column name in R?

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.我想使用行名和列名获取值 11。 how to extract value 11 from data frame.如何从数据框中提取值 11。 i tried below code for this but didn't give me results it's either giving me NA or NULL我为此尝试了下面的代码,但没有给我结果它要么给我 NA 要么 NULL

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

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


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

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'它不是行名属性,而是列“A”因此,使用“A”列创建一个逻辑索引,将其用作行索引,同时将该列指定为“columnName”

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

You can try subset like below您可以尝试如下subset

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

Using df defined reproducibly in the Note at the end在最后的注释中使用可重复定义的 df

1) use subset as shown. 1)如图所示使用子集。

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. 2)假设行名是唯一的另一种可能性是使它们成为真正的行名,删除包含它们的列。 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)

If you assign column A as your row names, then you can search using the indexing.如果将A列指定为行名称,则可以使用索引进行搜索。

> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM