[英]Change values in row based on a column value and replacing specified column range
[英]R-Changing row values based on a value specified by a column
我有下面的數據集(df)。 “數字”列表示每行中需要將其值更改為5的列數。
Col1 Col2 Col3 Col4 Col5 Col6 Col7 Num
0 1 1 1 1 0 0 3
0 0 1 1 1 1 1 3
0 0 0 1 1 1 0 2
0 0 0 1 0 1 0 5
1 1 1 1 1 1 1 6
我得到的數據集看起來像這樣:
Col1 Col2 Col3 Col4 Col5 Col6 Col7 Num
5 5 5 1 1 0 0 3
5 5 5 1 1 1 1 3
5 5 0 1 1 1 0 2
5 5 5 5 5 1 0 5
5 5 5 5 5 5 1 6
我使用了以下命令,但它僅根據列的第一行更改值。
for (i in 1:length (df$Num)){
df[,1:i]=5
}
如果有人指出我在做什么錯,我將不勝感激。
嘗試
df[cbind(rep(1:nrow(df), df$Num), sequence(df$Num))] <- 5
df
# Col1 Col2 Col3 Col4 Col5 Col6 Col7 Num
#1 5 5 5 1 1 0 0 3
#2 5 5 5 1 1 1 1 3
#3 5 5 0 1 1 1 0 2
#4 5 5 5 5 5 1 0 5
#5 5 5 5 5 5 5 1 6
df <- structure(list(Col1 = c(0L, 0L, 0L, 0L, 1L), Col2 = c(1L, 0L,
0L, 0L, 1L), Col3 = c(1L, 1L, 0L, 0L, 1L), Col4 = c(1L, 1L, 1L,
1L, 1L), Col5 = c(1L, 1L, 1L, 0L, 1L), Col6 = c(0L, 1L, 1L, 1L,
1L), Col7 = c(0L, 1L, 0L, 0L, 1L), Num = c(3L, 3L, 2L, 5L, 6L
)), .Names = c("Col1", "Col2", "Col3", "Col4", "Col5", "Col6",
"Col7", "Num"), class = "data.frame", row.names = c(NA, -5L))
如果您想要循環解決方案,那就是
for (i in 1:length (df$Num)){
df[i,1:df$Num[i]]=5
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.