简体   繁体   中英

Subsetting data.frame in in specific order in R (for setting vertex attributes)

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

name  age
a     10
b     20
c     30

and I have a list of names cbd . 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

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM