首页 > 解决方案 > How can I select rows of a data frames if column is a list?

问题描述

I'm kinda new in R development.

I'm retrieving data from a MongoDB instance to R using mongolite. I want to retrieve all the records, so R can put them into a data frame and then iterate over it, like selecting specified rows by column value.

The problem is that one of the columns is a data frame too. See the example above. How can I access to column coordinates selecting only 9.125, 36.125?

I tried with:

df[df$location$coordinates == coords,]

where coords is

 [[1]]
 [1]  9.125 37.125

but I receive comparison of these types is not implemented

Where am I wrong? Type of coords or selecting over the data frame? Thank you.

Input

location.type ---- location.coordinates ---- value 
Point              9.125, 37.125             1   
Point              9.125, 36.125             2
Point              8.125, 37.125             3   

Output expected

location.type ---- location.coordinates ---- value 
Point              9.125, 37.125             2

After 2st comment I tried

  coords[[1]]

receiving (list) object cannot be coerced to type 'double'

  dput(head(df))

  structure(list(location = structure(list(type = c("Point", "Point", 
  "Point"), coordinates = list(c(9.125, 
  37.125), c(9.125, 36.125), c(8.125, 37.125))), row.names = c(NA, 6L
  ), class = "data.frame"), value = 1:3))

标签: rmongodblistdataframeselect

解决方案


Here is a solution using %in%:

df <- data.frame(location.type = rep("Point", 3))
df$location.coordinates <- list(c(9.125, 37.125), c(9.125, 36.125), c(8.125, 37.125))
df$value <- 1:3


df[df$location.coordinates %in% coords,]
  location.type location.coordinates value
1         Point        9.125, 37.125     1

推荐阅读