复制并追加到R中的数据框

时间:2019-06-20 18:04:01

标签: r dataframe data-manipulation replicate

我相信这很简单,尽管我不熟悉R和代码。我有一个数据集,其中每个啮齿动物陷阱位点都有一行。但是,在4年中有8次被困的情况。我想做的是扩展陷阱站点数据,并为每行附加一个数字1至8。

然后,我可以用陷阱访问标记它们,以便随后使用获得的陷阱数据进行联接。

我设法用以下代码复制行。当行在数据框中扩展为1、1.1 ... 1.7、2、2.1 ... 2.7等时,我无法弄清楚如何将其转换为基于列的可用ID。

structure(list(TrapCode = c("IA1sA", "IA2sA", "IA3sA", "IA4sA", 
"IA5sA"), Y = c(-12.1355987315, -12.1356879776, -12.1357664998, 
-12.1358823313, -12.1359720852), X = c(-69.1335789865, -69.1335225279, 
-69.1334668485, -69.1333847769, -69.1333226532)), row.names = c(NA, 
5L), class = "data.frame")

gps_1 <– gps_1[rep(seq_len(nrow(gps_1)), 3), ]

给予

"IA5sA", "IA1sA", "IA2sA", "IA3sA", "IA4sA", "IA5sA", "IA1sA", 
"IA2sA", "IA3sA", "IA4sA", "IA5sA"), Y = c(-12.1355987315, -12.1356879776, 
-12.1357664998, -12.1358823313, -12.1359720852, -12.1355987315, 
-12.1356879776, -12.1357664998, -12.1358823313, -12.1359720852, 
-12.1355987315, -12.1356879776, -12.1357664998, -12.1358823313, 
-12.1359720852), X = c(-69.1335789865, -69.1335225279, -69.1334668485, 
-69.1333847769, -69.1333226532, -69.1335789865, -69.1335225279, 
-69.1334668485, -69.1333847769, -69.1333226532, -69.1335789865, 
-69.1335225279, -69.1334668485, -69.1333847769, -69.1333226532
)), row.names = c("1", "2", "3", "4", "5", "1.1", "2.1", "3.1", 
"4.1", "5.1", "1.2", "2.2", "3.2", "4.2", "5.2"), class = "data.frame")

我有一列,其中Trap_ID当前是唯一标识符。我希望复制后可以在其中附加一个迭代编号,以使其保持唯一ID。

例如:

Trap_ID
IA1sA.1
IA1sA.2
IA1sA.3
IA2sA.1
IA2sA.2
IA2sA.3

1 个答案:

答案 0 :(得分:1)

只需使用交叉连接(即不使用 by 列进行连接即可返回两个集合的笛卡尔积):

mdf <- merge(data.frame(Trap_ID = 1:8), trap_side_df, by=NULL)