有条件地替换R中列中的所有值
我有这样一个数据帧:有条件地替换R中列中的所有值,r,dplyr,R,Dplyr,我有这样一个数据帧: eh1 <- c(1,1,1,1,1,1,1,1) eh2 <- c(0,0,1,0,0,0,0,0) mydata <- data.frame(eh1, eh2) 我不想要一个特定于示例数据的行和列的答案,但我可以在dplyr管道或for循环中应用更通用的代码 我认为这是一个简单的一个,但由于某些原因,我有麻烦!非常感谢 您可以将值设置为0,其中eh1=1,行号在eh2中第一次出现1之后 library(dplyr) mydata %>% m
eh1 <- c(1,1,1,1,1,1,1,1)
eh2 <- c(0,0,1,0,0,0,0,0)
mydata <- data.frame(eh1, eh2)
我不想要一个特定于示例数据的行和列的答案,但我可以在dplyr
管道或for
循环中应用更通用的代码
我认为这是一个简单的一个,但由于某些原因,我有麻烦!非常感谢 您可以将值设置为0,其中
eh1=1
,行号在eh2
中第一次出现1之后
library(dplyr)
mydata %>%
mutate(eh1 = replace(eh1, row_number() > which(eh2==1)[1] & eh1 == 1, 0))
#mutate(eh1 = replace(eh1, row_number() > which.max(eh2) & eh1 == 1, 0))
#mutate(eh1 = replace(eh1, lag(cummax(eh2) > 0 & eh1 == 1), 0))
#mutate(eh1 = replace(eh1, lag(cumsum(eh2) > 0) & eh1 == 1, 0))
# eh1 eh2
#1 1 0
#2 1 0
#3 1 1
#4 0 0
#5 0 0
#6 0 0
#7 0 0
#8 0 0
可以将其转换为基本R:
transform(mydata,eh1 = replace(eh1,seq_along(eh2) > which.max(eh2) & eh1 == 1, 0))
您可以将值设置为0,其中
eh1=1
,行号在eh2
中第一次出现1之后
library(dplyr)
mydata %>%
mutate(eh1 = replace(eh1, row_number() > which(eh2==1)[1] & eh1 == 1, 0))
#mutate(eh1 = replace(eh1, row_number() > which.max(eh2) & eh1 == 1, 0))
#mutate(eh1 = replace(eh1, lag(cummax(eh2) > 0 & eh1 == 1), 0))
#mutate(eh1 = replace(eh1, lag(cumsum(eh2) > 0) & eh1 == 1, 0))
# eh1 eh2
#1 1 0
#2 1 0
#3 1 1
#4 0 0
#5 0 0
#6 0 0
#7 0 0
#8 0 0
可以将其转换为基本R:
transform(mydata,eh1 = replace(eh1,seq_along(eh2) > which.max(eh2) & eh1 == 1, 0))
我们可以使用
match
library(dplyr)
mydata %>%
mutate(eh1 = +(row_number() <= match(1, eh2)) )
# eh1 eh2
#1 1 0
#2 1 0
#3 1 1
#4 0 0
#5 0 0
#6 0 0
#7 0 0
#8 0 0
我们可以使用
match
library(dplyr)
mydata %>%
mutate(eh1 = +(row_number() <= match(1, eh2)) )
# eh1 eh2
#1 1 0
#2 1 0
#3 1 1
#4 0 0
#5 0 0
#6 0 0
#7 0 0
#8 0 0