[英]Adding row of one data frame at a specific spot in another dataframe in R
我有一個 5520 x 5520 的大數據框。在每 120 行之后我需要添加另一行。 到 5520 時,這些新行的值包含在一行的數據框中。
使用 rbind 我將這些行添加到我不想要的表的末尾。 並給我一個錯誤: fabioN2 <-rbind(fabioN2, auf2[1,]) Error in match.names(clabs, names(xi)): names do not match previous names
將 tibble 與 add_row 一起使用我也收到錯誤: > fabioN2 %>% add_row(fabioN2, auf2[1,], .after = 120) Error: New rows can't add columns. x Can't find columns
> fabioN2 %>% add_row(fabioN2, auf2[1,], .after = 120) Error: New rows can't add columns. x Can't find columns
fabioN2 ,
X1 ,
X2 ,
X3 ,
X4 , and 5516 more in
.
fabioN2 是大的 dataframe 和 auf2 包含我想添加到 fabioN2 的值。 毫無疑問,代碼是錯誤的,並且基於錯誤,我必須匹配兩個數據幀的列名,考慮到 5520 個不同的列名,我想避免這種情況。
任何人都知道如何輕松地將這些數據幀添加到所需的位置?
我希望我的邏輯適合你的問題......我為 30 行的數據幀做了每 10 行添加一行(因為 120 對於在答案中擬合 output 的可重現示例來說太多了).
library(dplyr)
r <- 3 # your number is 46 (5520/120)
l <- 10 # your number is 120
# your long data.frame where you want to fit in ever l rows
df1 <- data.frame(dx = c("a","a","a","a","a","a","a","a","a","a",
"c","c","c","c","c","c","c","c","c","c",
"e","e","e","e","e","e","e","e","e","e"))
# your data.frame of one row to fit in every l rows
df2 <- data.frame(dy = c("X"))
# set colnames to be identical
names(df2) <- colnames(df1)
# use row number as ID and set it of as needed with the help of integer division
dff1 <- df1 %>%
dplyr::mutate(ID = dplyr::row_number()) %>%
dplyr::mutate(ID = ID + (ID-1) %/% l)
# repeat your one row df according to the quantity needed and use the row number with set off calculation
dff2 <- df2 %>%
dplyr::slice(rep(row_number(), r)) %>%
dplyr::mutate(ID = dplyr::row_number()) %>%
dplyr::mutate(ID = (ID) * l + ID)
# union both data.frames (I am supposing column types are identical!)
dff1 %>%
dplyr::union(dff2) %>%
dplyr::arrange(ID)
dx ID
1 a 1
2 a 2
3 a 3
4 a 4
5 a 5
6 a 6
7 a 7
8 a 8
9 a 9
10 a 10
11 X 11
12 c 12
13 c 13
14 c 14
15 c 15
16 c 16
17 c 17
18 c 18
19 c 19
20 c 20
21 c 21
22 X 22
23 e 23
24 e 24
25 e 25
26 e 26
27 e 27
28 e 28
29 e 29
30 e 30
31 e 31
32 e 32
33 X 33
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.