5

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
  • 51,121
  • 6
  • 32
  • 66
Niranjan Agnihotri
  • 916
  • 2
  • 11
  • 19
  • 2
    If you use `lapply` and getting this as an output, consider using [`sapply`](https://stackoverflow.com/a/7141669/1030110). – m0nhawk May 31 '17 at 06:33
  • What you get with just `v1 <- unlist(allsum)` is a named vector, which is still a numeric vector. For example you can try `v1 + 1000` or do `as.data.frame(v1)`, or `names(v1)` and `unname(v1)` – Sotos May 31 '17 at 07:20
  • Perfect @Sotos I thing unname() is the right thing to do!! Thanks!! – Niranjan Agnihotri May 31 '17 at 07:27

4 Answers4

12

@Sotos thanks a lot.

I think I was just looking for this!!

unname(unlist(allsum))

Niranjan Agnihotri
  • 916
  • 2
  • 11
  • 19
7

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,756
  • 6
  • 37
  • 52
4

Please, try

as.integer(allsum)
#[1] 7332967 5635780 5454703 3464206
Uwe
  • 41,420
  • 11
  • 90
  • 134
0

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

unlist(allsum)
Pop
  • 12,135
  • 5
  • 55
  • 68