1

I have a vector, i.e. a list that includes 107 country names and values, and a matrix with 203 country names and values. I would like to adjust the list to match the matrix by row names, so that matching country names and values get included and other countries are filled with NA.

Here is a reproducible example. As you can see, Afghanistan is not included in the vector but in the matrix since the matrix includes more countries.

#vector
df <- read.table(header=TRUE, 
text="Area Value             
Albania 2758
Angola  64772
Argentina   266403082
Australia   251000
Austria 784684
")

#matrix
Z <- matrix(1:25, nrow = 5, ncol = 5, byrow=TRUE, dimnames = list(c("Afghanistan","Albania","Algeria","Argentina","Australia"), c("Afghanistan","Albania","Algeria","Argentina","Australia")))

How can I do this?

MoonS
  • 117
  • 7

1 Answers1

0

You can create a dataframe of rownames from matrix and merge with df :

result <- merge(data.frame(Area = rownames(Z)), df, all.x = TRUE, by = 'Area')
result

#         Area     Value
#1 Afghanistan        NA
#2     Albania      2758
#3     Algeria        NA
#4   Argentina 266403082
#5   Australia    251000
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Brilliant, thank you! Can I use as.numeric somehow in this code to make sure the result is numeric? – MoonS Oct 15 '20 at 13:12
  • What do you mean? I see `class(result$Value)` as integer for your given example. – Ronak Shah Oct 15 '20 at 15:08
  • When trying to calculate the list and matrix together by df + rowSums(Z), I got the error message In "Ops.factor(left, right) : ‘+’ not meaningful for factors". So I figured df or Z must not be numeric? – MoonS Oct 15 '20 at 17:16
  • @JohannaH But `result` has `Area` column which is not numeric. Try something like this : `replace(result$Value, is.na(result$Value), 0) + rowSums(Z, na.rm = TRUE)` . – Ronak Shah Oct 15 '20 at 23:44
  • Worked perfectly, thank you so much! – MoonS Oct 16 '20 at 06:32
  • @ Ronak Shah I see now this command removes my row and column names. Is there a way to keep them? – MoonS Oct 28 '20 at 15:33