简体   繁体   English

在 R dataframe 中查找值的单元格引用

[英]Find a cell reference for a value in a R dataframe

I am trying to find a way to search within a dataframe to return the column and row reference for multiple conditions.我试图找到一种在 dataframe 中搜索的方法,以返回多个条件的列和行引用。

#some data 
SalesData<-data.frame(Appliance=c("Radio", "Laptop", "TV", "Fridge"), ThisYear=c(5,25,5,8), LastYear=c(6,20,5,8))

 #code to find which row column TV is in which correctly gives row 3, col 1
 TVRef<-which(SalesData==("TV"), arr.ind=TRUE)

In the SalesData dataframe I would want to search for the dataframe (row, column) reference where Appliance = TV and where LastYear = 5.在 SalesData dataframe 中,我想搜索 dataframe(行、列)参考,其中 Appliance = TV,LastYear = 5。

I know how to search for a single item in R as per the above code but I don't know how to do this for multiple items.我知道如何根据上面的代码在 R 中搜索单个项目,但我不知道如何为多个项目执行此操作。 For this example I would want to return the result row 3, col 3 so I could then reuse this in further code to update the dataframe.对于这个例子,我想返回结果第 3 行,第 3 列,这样我就可以在进一步的代码中重用它来更新 dataframe。

Is there anything anyone can suggest?有什么人可以建议的吗?

You can use a logical and ( & ) and pass multiple condition to row selector as follows:您可以使用逻辑and ( & ) 并将多个条件传递给行选择器,如下所示:

SalesData[c(SalesData$Appliance=="TV" & SalesData$LastYear==5),][[3]]
#[1] 5

An alternative using with can be done follows:可以使用with的替代方法如下:

with(SalesData, SalesData[Appliance=="TV" & LastYear==5,][[3]])
#[1] 5

This is a numeric output which you can do这是一个数字 output 你可以做

SalesData[c(SalesData$Appliance=="TV" & SalesData$LastYear==5),][[3]] <- 500
# To replace it with say 500. 

I like using dplyr functions that make it read pretty easily我喜欢使用 dplyr 函数,使其易于阅读

SalesData<-data.frame(Appliance=c("Radio", "Laptop", "TV", "Fridge"), ThisYear=c(5,25,5,8), LastYear=c(6,20,5,8))


library(dplyr)


SalesData %>% 
  filter(Appliance == "TV" & LastYear == 5)

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

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