R 如何基于其他列在列中给定值

R 如何基于其他列在列中给定值,r,R,我有一个df如下 V1| V2| V3| V4 --+---+---+--- 10| 1 | 3 | 2 2 | 1 | 1 | 0 0 | 3 | 0 | 2 2 | 0 | 1 | 1 0 | 0 | 2 | 3 2 | 2 | 0 | 4 我想写一个程序,这样 如果V1!=0那么V2、v3、v4都将是0 类似地,如果V1==0和V2!=然后V3、V4为零,依此类推 我正在尝试for循环和if语句,但没有成功。有人能帮忙吗 预期产量 V1| V2| V3| V4 --+---+---+--

我有一个df如下

V1| V2| V3| V4
--+---+---+---
10| 1 | 3 | 2
2 | 1 | 1 | 0
0 | 3 | 0 | 2
2 | 0 | 1 | 1
0 | 0 | 2 | 3
2 | 2 | 0 | 4
我想写一个程序,这样 如果V1!=0那么V2、v3、v4都将是0 类似地,如果V1==0和V2!=然后V3、V4为零,依此类推

我正在尝试for循环和if语句,但没有成功。有人能帮忙吗

预期产量

V1| V2| V3| V4
--+---+---+---
10| 0 | 0 | 0 
2 |0  | 0 | 0
0 | 3 | 0 | 0 
2 | 0 | 0 | 0 
0 | 0 | 2 | 0 
2 | 0 | 0 | 0 

我原以为这件事能和max.col一起解决,但我想不出办法。这是一个漫长的过程

#For each row find out its 1st value which is greater than zero
indx <- max.col(df > 0, ties.method = "first")

#Convert the dataframe to matrix
mat <- as.matrix(t(df))

#Get the indices which we need to convert to zero
indices <- setdiff(1:(nrow(df) * ncol(df)), rep(ncol(df), length(indx)) * 
                                            (seq_along(indx) - 1) + indx)

#The output of rep(ncol(df), length(indx)) * (seq_along(indx) - 1) + indx is 
#[1]  1  5 10 13 19 21 
#which are the indices which we don't want to change to zero.

# Convert those indices to zero
mat[indices] <- 0
data.frame(t(mat))


#  V1 V2 V3 V4
#  10  0  0  0
#   2  0  0  0
#   0  3  0  0
#   2  0  0  0
#   0  0  2  0
#   2  0  0  0

请提供可复制的示例和预期输出。请描述您已经完成的工作以及结果中的错误。