1

I have information in a data.frame containing of two columns e.g.:

name  age
a     10
b     20
c     30

and I have a list of names c b d. Now I want to obtain a data.frame (or list or anything) of the attributes of the original data frame in the order of the list. For the above example, that would be

name  age
c     30
b     20
d     NA

I feel that this shouldn't be too difficult (even in-line maybe) but I can't find a way to do it in R.

Background:

I have a 'network' object created from an edge list. I have another of vertex-attributes, but no power over how each of these is ordered initially. Now I want assign the network vertices these attributes.

But in order to use

  • network %v% "age" <- dataframe[,2] I'd need the data frame to be in the right order

and for

  • set.vertex.attribute(network, "age", hhs$age, v = hhs$di) I'd need the vertex ids
josliber
  • 43,891
  • 12
  • 98
  • 133
sheß
  • 484
  • 4
  • 20

2 Answers2

4

I took your list of names ls and made it a data.frame with the same name name.

I then used left_join from dplyr

ls<-c("c","b","d")
df2<-data.frame(name=ls)

df2 %>% left_join(df,by="name")->new_df

> new_df
  name age
1    c  30
2    b  20
3    d  NA

Or, if you're unfamiliar with the dplyr/magrittr piping, you could re-write this as:

new_df<-left_join(df2,df,by="name")

As it yields the same result:

> new_df
  name age
1    c  30
2    b  20
3    d  NA

In fact, since df2 only has name, you don't even need to specify the by= argument.

new_df<-left_join(df2,df)

yields the same result.

Andrew Taylor
  • 3,438
  • 1
  • 26
  • 47
0

This can be done in a single line in base R with the match function:

data.frame(name=names, age=df$age[match(names, df$name)])
#   name age
# 1    c  30
# 2    b  20
# 3    d  NA

Data:

names <- c("c", "b", "d")
df <- data.frame(name=c("a", "b", "c"), age=c(10, 20, 30))
josliber
  • 43,891
  • 12
  • 98
  • 133