簡體   English   中英

R將數據框與向量合並

[英]R merging a dataframe with a vector

我有一個看起來像這樣的數據框 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 中給出的 indx 的 adj_coords。 它應該看起來像:

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_coords 進行采樣,這樣我就有了類似的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM