我有这样两列数据:

v1 = c(0, 29, 32, 29, 32, 28, -59, 30)
v2 = c(0, 0, 0, 0, 1, 1, 0, 1)

data = data.frame(v1, v2)

   v1 v2
1   0  0
2  29  0
3  32  0
4  29  0
5  32  1
6  28  1
7 -59  0
8  30  1

我想按如下方式更改v2列的值:如果v1的值为负,那么将v2之前的所有1s更改为0.我可以使用R应用for循环来实现这一点.有没有一种方法可以在不应用for循环的情况下做同样的事情(可能使用dplyr包)?

Update My actual problem is more general than the situation I explained earlier. I apologize for the confusion. My data can have more than one negative values like in the given example: enter image description here

推荐答案

dplyr溶液,cumsum()确定位置,其中v1 < 0:

library(dplyr)

data %>%
  mutate(v2 = ifelse(row_number() < which.max(cumsum(v1 < 0)), 0, v2))

   v1 v2
1   0  0
2  29  0
3  32  0
4  29  0
5  32  0
6  28  0
7 -59  0
8  30  1

如果数据有多个负值:

data <- data.frame(v1 = c(0, 29, 32, 60, -30, 31, -31, 31),
                   v2 = c(0,  0,  0,  1,   0,  1,   0,  1))

我的代码给出(result列):

   v1 v2 result
1   0  0      0
2  29  0      0
3  32  0      0
4  60  1      0
5 -30  0      0
6  31  1      0
7 -31  0      0
8  31  1      1

R相关问答推荐

在边界外添加注释或标题

在R底座中更改白天和夜晚的背景 colored颜色

将年度数据插入月度数据

Highcharter多次钻取不起作用,使用不同方法

手动打印线型gplot

如何编辑ggplot的图例字使用自定义对象(gtable)?'

derrr mutate case_when grepl不能在R中正确返回值

如何在modelsummary中重命名统计数据?

如果某些列全部为NA,则更改列

将饼图插入条形图

展开对数比例绘图的轴(添加填充)

如何将SAS数据集的列名和列标签同时包含在r中GT表的表首?

您是否可以使用facet_rap设置一个较低的限制来对ggmap上的比例中断进行zoom ?

过滤名称以特定字符串开头的文件

有没有可能用shiny 的书签恢复手风琴面板?

我如何go 掉盒子图底部的数字?

我如何使用tidyselect来传递一个符号数组,比如Pivot_Long?

使用ifElse语句在ggploy中设置aes y值

填充图例什么时候会有点?

将CSV转换为R中的自定义JSON格式