简体   繁体   中英

Is there a R function to find make column values based on one column variable?

I am trying to get spatial coordinates of related objects into new columns based on relationship identities in another column. However, I haven't managed to figure out the right way to do so. Here's what my data frame looks like

    object   parent x-pos y-pos
 1:     Z        A 0.5 0.7
 2:     B        A 0.1 0.0
 3:     C        E 4.6 2.5
 4:     D        E 5.6 5.0
 5:     A        B 0.2 1.0
 6:     P        B 0.4 2.0

What I want to add to this data frame is two new columns of x-pos-parent and y-pos-parent based on the parent information in the "parent column", for every unique object in the "object" column? Any help would be greatly appreciated...

The expected df should look

like so
     object   parent x-pos y-pos x-pos-parent y-pos-parent
 1:     Z        A   0.5   0.7   0.2          1.0
 2:     B        A   0.1   0.0   0.2          1.0

If this only goes one deep, you could do a left_join or equivalent:

library(dplyr)

DF%>%
  left_join(., ., by = c('parent' = 'object'))%>%
  select(-parent.y)

  object parent x.pos.x y.pos.x x.pos.y y.pos.y
1      Z      A     0.5     0.7     0.2       1
2      B      A     0.1     0.0     0.2       1
3      C      E     4.6     2.5      NA      NA
4      D      E     5.6     5.0      NA      NA
5      A      B     0.2     1.0     0.1       0
6      P      B     0.4     2.0     0.1       0

You can also do a data.table update join:

DT <- as.data.table(DF)
DT[DT
   , on = .(parent = object)
   , `:=`(x_pos_par = i.x.pos
          , y_pos_par = i.y.pos)]

DT
   object parent x.pos y.pos x_pos_par y_pos_par
1:      Z      A   0.5   0.7       0.2         1
2:      B      A   0.1   0.0       0.2         1
3:      C      E   4.6   2.5        NA        NA
4:      D      E   5.6   5.0        NA        NA
5:      A      B   0.2   1.0       0.1         0
6:      P      B   0.4   2.0       0.1         0

If you have more than one level of recursion, you should look into the package igraph .

Data

Lines <- "object   parent x-pos y-pos
1     Z        A 0.5 0.7
2     B        A 0.1 0.0
3     C        E 4.6 2.5
4     D        E 5.6 5.0
5     A        B 0.2 1.0
6     P        B 0.4 2.0"
DF <- read.table(text = Lines)

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