从一列到下一个给定条件的复制值
我的二进制数据如下:
ID <- c("A", "B", "C", "D", "E", "F")
Q0 <- c(0, 0, 0, 0, 0, 0)
Q1 <- c(0, 1, 0, 0, NA, 1)
Q2 <- c(0, NA, 1, 0, NA, 1)
Q3 <- c(0, NA, NA, 1, NA, 1)
Q4 <- c(0, NA, NA, 1, NA, 1)
dta <- data.frame(ID, Q0, Q1, Q2, Q3, Q4)
如果其中一列中有1行,则所有后续列也应为1。如果有0或NA,则下一个列应该保持原样。
陈述不同,如何根据相对位置处的列值有条件地更改多个列的值?
上述数据框架的预期输出是:
ID Q0 Q1 Q2 Q3 Q4
A 0 0 0 0 0
B 0 1 1 1 1
C 0 0 1 1 1
D 0 0 0 1 1
E 0 NA NA NA NA
F 0 1 1 1 1
我该怎么做?也许使用应用
或循环的?
I have binary data as below:
ID <- c("A", "B", "C", "D", "E", "F")
Q0 <- c(0, 0, 0, 0, 0, 0)
Q1 <- c(0, 1, 0, 0, NA, 1)
Q2 <- c(0, NA, 1, 0, NA, 1)
Q3 <- c(0, NA, NA, 1, NA, 1)
Q4 <- c(0, NA, NA, 1, NA, 1)
dta <- data.frame(ID, Q0, Q1, Q2, Q3, Q4)
If there is 1 for a row in one of the columns, all the subsequent columns should be 1 as well. If there is 0 or NA, the next column should stay as is.
Stated differently, how can I change the value of multiple columns based conditionally on the value of a column in a relative position?
The intended output for the above data frame is:
ID Q0 Q1 Q2 Q3 Q4
A 0 0 0 0 0
B 0 1 1 1 1
C 0 0 1 1 1
D 0 0 0 1 1
E 0 NA NA NA NA
F 0 1 1 1 1
How can I do this? Perhaps using apply
or a for
loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
另一个
dplyr
+purrr
选项可能是:Yet another
dplyr
+purrr
option could be:通过循环保持简单:
使用
dplyr
+data.table
受Yuriy的启发:Keeping things simple with a loop:
With
dplyr
+data.table
inspired by Yuriy:带有
na.locf
的选项-Output
An option with
na.locf
-output
我发现了一个枢纽:
I found one more with pivoting:
另一个可能的解决方案:
Another possible solution:
由
Created on 2022-07-04 by the reprex package (v2.0.1)
在相同的
突变
中创建所有变量您可以
You can create all the variables in the same
mutate
But I don't know if it's possible to do this more programmatically
这是
应用
的基本r方式。由
Here is a base R way with
apply
.Created on 2022-07-04 by the reprex package (v2.0.1)