1

I have a dataframe, df:

   z  x  y 
a  T  1  F 
b  T  4  F
g  F  7  T
a  T  1  F
d  T  2  T
d  T  2  T
b  T  4  F
g  F  7  T

I also have a vector, v1, like the following:

a  1
e  5
b  2
g  3
d  4
f  6

What I want to do is add this vector to my existing dataframe for only the rows that already exist in the dataframe:

   z  x  y new 
a  T  1  F  1
b  T  4  F  2
g  F  7  T  3
a  T  1  F  1
d  T  2  T  4
d  T  2  T  4
b  T  4  F  2
g  F  7  T  3

in psuedocode I want to do something like

for i in rownames(df):
    if i in rownames(v1):
        add v1 value of i to a new column, df$new
BOBjwjwj3j3j
  • 141
  • 6
  • Can you share `dput(df)` and `dput(v1)` ? `v1` looks more like a dataframe to me. – markus Dec 11 '20 at 19:11
  • I guess you have a matrix instead of data.frame because data.frame wouldn't allow duplicate row names – akrun Dec 11 '20 at 19:13

1 Answers1

3

We can do an assignment based on the names of the vector. Assuming that the object is a matrix as duplicate row names are not allowed in data.frame

m2 <- cbind(m1, new = v1[row.names(m1)])

-output

m2
#   z   x   y   new
#a "T" "1" "F" "1"
#b "T" "4" "F" "2"
#g "F" "7" "T" "3"
#a "T" "1" "F" "1"
#d "T" "2" "T" "4"
#d "T" "2" "T" "4"
#b "T" "4" "F" "2"
#g "F" "7" "T" "3"

data

m1 <- structure(c("T", "T", "F", "T", "T", "T", "T", "F", "1", "4", 
"7", "1", "2", "2", "4", "7", "F", "F", "T", "F", "T", "T", "F", 
"T"), .Dim = c(8L, 3L), .Dimnames = list(c("a", "b", "g", "a", 
"d", "d", "b", "g"), c("z", "x", "y")))

v1 <- c(a = 1, e = 5, b = 2, g = 3, d = 4, f = 6)
akrun
  • 874,273
  • 37
  • 540
  • 662