繁体   English   中英

R更改基于列指定的值的行值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM