复制R中的数据框的行 [英] Copy rows of dataframes in R
本文介绍了复制R中的数据框的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框:
df <- data.frame(id = c('1','2','3'), b = c('b1', '', 'b3'), c = c('c1', 'c2', ''), d = c('d1', '', ''))
id b c d
1 b1 c1 d1
2 c2
3 b3
其中 id-1
的行被所有没有空列值的数据填充。我想将所有单元格值从 id-1
复制到 id 2和3
,如果这些单元格中缺少值从行2开始3
。最终输出如下:
where the row with id-1
is filled with all data with no empty column values. I want to copy all cell values from id-1
into id 2 and 3
if there are missing values in those cells from rows 2 & 3
. Final output something like:
df2 <- data.frame(id = c('1','2','3'), b = c('b1', 'b1', 'b3'), c = c('c1', 'c2', 'c1'), d = c('d1', 'd1', 'd1'))
id b c d
1 b1 c1 d1
2 b1 c2 d1
3 b3 c1 d1
谢谢您的帮助
推荐答案
使用一些矩阵索引来获取
的情况,然后覆盖从 df
第一行中选择适当的列:
Use some matrix indexing to get the ""
cases and then overwrite selecting the appropriate column from the first row of df
:
idx <- which(df[-1]=="", arr.ind=TRUE)
df[-1][idx] <- unlist(df[1,-1][idx[,"col"]])
# id b c d
#1 1 b1 c1 d1
#2 2 b1 c2 d1
#3 3 b3 c1 d1
这篇关于复制R中的数据框的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文