有条件地填充数据帧的行

efb*_*own 5 r dataframe

我有一个这个结构的数据框,我想填充:

    V1      V2  V3  V4  V5  V6  V7  V8
1   ID_CODE 0   0   0   0   0   0   0
2   THIS    0   0   0   0   0   0   0
3   ISAROW  0   0   0   0   0   0   0
4   01      0   0   0   0   0   0   0
5   02      0   0   0   0   0   0   0
6   03      0   0   0   0   0   0   0
7   ID_CODE 0   0   0   0   0   0   0
8   THESE   0   0   0   0   0   0   0
9   ARE     0   0   0   0   0   0   0
10  MORE    0   0   0   0   0   0   0
11  ROWS    0   0   0   0   0   0   0
12  01      0   0   0   0   0   0   0
13  02      0   0   0   0   0   0   0
14  03      0   0   0   0   0   0   0
15  ROW     0   0   0   0   0   0   0
Run Code Online (Sandbox Code Playgroud)

这个数据框用数字来填充它:

  V2_1 V2_2 V2_3 V2_4 V2_5 V2_6 V2_7
1 786  786  786  786  786  786  786
2 786  786  786  786  786  786  786
3 78   78   78   78   78   78   78
4 78   78   78   78   78   78   78
5 78   78   78   78   78   78   78
6 78   78   78   78   78   78   78
Run Code Online (Sandbox Code Playgroud)

这些数字将进入V2:V8列,并且仅在V1为数字的行中.V1是一个字符串的行将保持为零.

Ric*_*ven 4

如果df1是原始的和df2替换的,那么我们就可以用Map子集来替换。

## find the rows with only digits in the first column
rows <- grepl("^\\d+$", df1$V1)
## replace the subset with 'df2'
df1[rows, -1] <- Map("[<-", df1[rows, -1], df2)
df1
#         V1  V2  V3  V4  V5  V6  V7  V8
# 1  ID_CODE   0   0   0   0   0   0   0
# 2     THIS   0   0   0   0   0   0   0
# 3   ISAROW   0   0   0   0   0   0   0
# 4       01 786 786 786 786 786 786 786
# 5       02 786 786 786 786 786 786 786
# 6       03  78  78  78  78  78  78  78
# 7  ID_CODE   0   0   0   0   0   0   0
# 8    THESE   0   0   0   0   0   0   0
# 9      ARE   0   0   0   0   0   0   0
# 10    MORE   0   0   0   0   0   0   0
# 11    ROWS   0   0   0   0   0   0   0
# 12      01  78  78  78  78  78  78  78
# 13      02  78  78  78  78  78  78  78
# 14      03  78  78  78  78  78  78  78
# 15     ROW   0   0   0   0   0   0   0
Run Code Online (Sandbox Code Playgroud)

或者,另一种方法是使用replace()

df1[rows, -1] <- Map(function(x, y) replace(x, rows, y), df1[-1], df2)
Run Code Online (Sandbox Code Playgroud)