R将数据帧与向量合并

  • 本文关键字:向量 合并 数据帧 r
  • 更新时间 :
  • 英文 :


我有一个数据框架df,看起来像这样:

indx          adj_coords
1    1    2, 3, 4, 5, 6, 7
2    2   1, 3, 7, 8, 9, 10
3    3 1, 2, 4, 10, 11, 12
4    4 1, 3, 5, 12, 13, 14
5    5 1, 4, 6, 14, 15, 16
6    6 1, 5, 7, 16, 17, 18

我还有一个向量vec它看起来像这样:

vec<-c(1,4,5,3,1)

我想得到一个长度为5的数据帧,其中每一行都有vec中给出的索引的adj_coord。它应该看起来像:

vec adj_coords
1   2, 3, 4, 5, 6, 7
4   1, 3, 5, 12, 13, 14
5   1, 4, 6, 14, 15, 16
3   1, 2, 4, 10, 11, 12
1   2, 3, 4, 5, 6, 7

之后,我想对adj_cods进行采样,这样我就有了这样的内容:

vec adj_coords              sampled_adj_coords
1   2, 3, 4, 5, 6, 7        3
4   1, 3, 5, 12, 13, 14     5
5   1, 4, 6, 14, 15, 16     14
3   1, 2, 4, 10, 11, 12     11
1   2, 3, 4, 5, 6, 7        6

为您做了一些尝试…看看是否有类似的东西你正在寻找…

vec <- c(1,4,5,3,1)
vec <- data.frame("vec"=vec, indx=vec)
df <- structure(list(indx = 1:6, adj_coords = list(2:7, c(1L, 3L, 7L, 8L, 9L, 10L), c(1L, 2L, 4L, 10L, 11L, 12L), c(1L, 3L, 5L, 12L, 13L, 14L), c(1L, 4L, 6L, 14L, 15L, 16L), c(1L, 5L, 7L, 16L, 17L, 18L))), row.names = c(NA, 6L), class = "data.frame")
library(dplyr)
inner_join(vec, df, by = 'indx')

结果:

vec indx          adj_coords
1   1    1    2, 3, 4, 5, 6, 7
2   4    4 1, 3, 5, 12, 13, 14
3   5    5 1, 4, 6, 14, 15, 16
4   3    3 1, 2, 4, 10, 11, 12
5   1    1    2, 3, 4, 5, 6, 7

删除不需要的列…

另一个选项:

df <- df[vec,]

输出:

indx          adj_coords
1      1    2, 3, 4, 5, 6, 7
4      4 1, 3, 5, 12, 13, 14
5      5 1, 4, 6, 14, 15, 16
3      3 1, 2, 4, 10, 11, 12
1.1    1    2, 3, 4, 5, 6, 7

对于随机样本,您可以使用:

df$sampled_adj_coords <- apply(df[-1], 1, function(x) {sample(unlist(x), 1)})

输出:

indx          adj_coords sampled_adj_coords
1      1    2, 3, 4, 5, 6, 7                  2
4      4 1, 3, 5, 12, 13, 14                 12
5      5 1, 4, 6, 14, 15, 16                  4
3      3 1, 2, 4, 10, 11, 12                  2
1.1    1    2, 3, 4, 5, 6, 7                  3

最新更新