简体   繁体   English

是否有R函数可根据一个列变量查找make列值?

[英]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? 我要添加到此数据框中的是基于“父级列”中父级信息的两个新的x-pos-parent和y-pos-parent列,针对“对象”列中的每个唯一对象? Any help would be greatly appreciated... 任何帮助将不胜感激...

The expected df should look 预期的df应该看起来

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: 如果只深入left_join ,则可以执行left_join或等效操作:

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: 您也可以执行data.table更新data.table

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 . 如果您有多个级别的递归,则应查看软件包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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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