2

I have a list with uniform size as below. I want to extract the values for the keys. How do I do it?

I have isolated the keys by using names(allsum) where allsum looks like this

`$1999
[1] 7332967

$2002
[1] 5635780

$2005
[1] 5454703

$2008
[1] 3464206`

I want [7332967, 5635780, 5454703, 3464206] as the output. I tried sapply but have a weak intuition. Please help.

for(a in allsum) {
  print(a[[1]])
}

I tried this, it works, but I want to know if we can do it with some function or without any explicit looping.

I tried using unlist Following is what happens

c1 <- unlist(allsum) 
 #1999    2002    2005    2008 
#7332967 5635780 5454703 3464206

I just need the big numbers. How do I extract?

Sotos
  • 47,396
  • 5
  • 31
  • 61
Niranjan Agnihotri
  • 646
  • 2
  • 9
  • 18

4 Answers4

9

@Sotos thanks a lot.

I think I was just looking for this!!

unname(unlist(allsum))

Niranjan Agnihotri
  • 646
  • 2
  • 9
  • 18
6

What about

allsum <- list(`1999` = 7332967, `2002` = 5635780, 
               `2005` = 5454703, `2008` = 3464206)   

paste(unlist(allsum))
# [1] "7332967" "5635780" "5454703" "3464206"

Edit:

As pointed out in the comments, paste will convert the numerical values in to strings.

You can either solve the problem create by paste(unlist(allsum)) with:

as.numeric(paste(unlist(allsum))
# [1] 7332967 5635780 5454703 3464206

Or avoid that issue altogether by using Sotos' suggestion in the comments:

unname(unlist(allsum))
# [1] 7332967 5635780 5454703 3464206
KenHBS
  • 6,185
  • 6
  • 37
  • 47
2

Please, try

as.integer(allsum)
#[1] 7332967 5635780 5454703 3464206
Uwe
  • 39,148
  • 11
  • 82
  • 123
0

To get, the values of list as a vector, you should do:

unlist(allsum)
Pop
  • 11,817
  • 4
  • 53
  • 67