-2

My list (sector_region) contains 2 elements. In those 2 elements there are multiple elements. How can I fetch these elements?

Following is my piece of code.

sector_region = unique(universe_database[, c("Region", "Sector")])
Phil
  • 4,344
  • 2
  • 23
  • 33
nidhi0806
  • 343
  • 3
  • 14
  • 1
    Can you make your example reproducible? See this post for help: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Phil May 21 '17 at 12:39
  • Try `lapply(sector_region, function(x) unique(x[, c("Region", "Sector")]))` – akrun May 21 '17 at 12:45
  • lapply is giving incorrect number of dimensions. Dont know the reason behind it. – nidhi0806 May 21 '17 at 12:56
  • 1
    Please show a small reproducible example and expected output – akrun May 21 '17 at 12:57
  • Let's say : employee <- c('John Doe','Peter Gynn','Jolie Hope','John Doe','Peter Gynn','Jolie Hope','John Doe','Peter Gynn','Jolie Hope','John Doe','Peter Gynn','Jolie Hope') salary <- c(21000, 23400, 26800,21000, 23400, 26800,21000, 23400, 26800,21000, 23400, 26800) universe_database <- data.frame(employee, salary,stringsAsFactors=FALSE) sector_region = unique(universe_database[,c("employee","salary")]) Now sector_region is a list. If I do sector_region[1] I will get a list of elements. How can I get single element like 'John Doe' ? – nidhi0806 May 21 '17 at 13:04
  • 1
    Add your code to your post. Do not put it in the comments. – lmo May 21 '17 at 13:14

1 Answers1

0

I quote your comment below:

Let's say : employee <- c('John Doe','Peter Gynn','Jolie Hope','John Doe','Peter Gynn','Jolie Hope','John Doe','Peter Gynn','Jolie Hope','John Doe','Peter Gynn','Jolie Hope') salary <- c(21000, 23400, 26800,21000, 23400, 26800,21000, 23400, 26800,21000, 23400, 26800) universe_database <- data.frame(employee, salary,stringsAsFactors=FALSE) sector_region = unique(universe_database[,c("employee","salary")]) Now sector_region is a list. If I do sector_region[1] I will get a list of elements. How can I get single element like 'John Doe'?

First of all, sector_region is a data frame, not a list. You can confirm that with class(sector_region). By the way, your code is equivalent to sector_region = unique(universe_database) since you only have two columns for universe_database.

To retrieve "John Doe" here, simply execute sector_region$employee[1] or sector_region[1, 1].

A more general solution would be sector_region$employee[sector_region$employee %in% "John Doe"]. Or, if you want to keep the returned values in a data frame, do subset(sector_region, employee %in% "John Doe", select = employee).

ytu
  • 1,822
  • 3
  • 19
  • 42