1

I have two list or vectors as the following in R:

vector 1
     d1    d2   d3   d4
2   0.75   1   0.25   0

vector 2
[1] "1" "3"

I need to add the values of vector 1 considering the values of vector2, I mean in my example to add the values of d1 plus d3 because vector 2 has those indexes. I was considering in using a for loop to traverse vector 2 and the adding the values of vector1, but is not other more direct way to perform this operation? I remember that it can be used by converting the indexes in T, F values, but frankly I quite don't remember.

Little
  • 3,363
  • 10
  • 45
  • 74

4 Answers4

2

Try this (the result is without order):

bool = gsub('d','',names(vector1)) %in% vector2

c(sum(vector1[bool]), vector1[!bool])

#   d2 d4 
# 1  1  0
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
2

Try:

sum(vector1[match(vector2, gsub("d", "", names(vector1)))])
[1] 1
DatamineR
  • 10,428
  • 3
  • 25
  • 45
1

Here's another approach with %in%

sum(v1[seq_along(v1) %in% v2])
# [1] 1
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
0

In this example, vector2 appears to be a character type containing the numerals of the indices of the positions from vector1 you want added. In this case the solution is even easier:

> vector1 <- c(d1=0.75, d2=1, d3=0.25, d4=0)
> vector1
  d1   d2   d3   d4 
0.75 1.00 0.25 0.00 
> vector2 <- c("1", "3")
> vector2
[1] "1" "3"
> sum(vector1[as.numeric(vector2)])
[1] 1

If you wanted to generalise this to a data.frame -- suggested by the layout of your "vector 1" that has a rowname of 2, then you could apply this to each row using:

> (df1 <- data.frame(d1=0:3, d2=10:13, d3=-1:2, d4=seq(.25, 1, .25)))
  d1 d2 d3   d4
1  0 10 -1 0.25
2  1 11  0 0.50
3  2 12  1 0.75
4  3 13  2 1.00
> apply(df1, 1, function(x) sum(x[as.numeric(vector2)]))
[1] -1  1  3  5
Ken Benoit
  • 14,454
  • 27
  • 50