我的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
我想写一个程序,所以 if(V1!= 0)则V2,v3,v4全部为0 类似地,如果V1 == 0且V2!= 0则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
答案 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