gpt4 book ai didi

r - 如果满足条件,则在行元素中创建空白

转载 作者:行者123 更新时间:2023-12-02 18:30:44 26 4
gpt4 key购买 nike

我的数据框如下:

              df <- data.frame(Resource_Code = c("B-T234","B-T234","B-T234"),
"Valid_To"= c("2021-10-17", "2021-11-28", "2021-10-31"),
"V1"= c("2021-10-17", "2021-10-17", "2021-10-24"),
"V2" = c("2021-10-24", "2021-10-31", "2021-10-31"),
"V3" = c("2021-10-31", "2021-11-07", "2021-11-14"),
"V4" = c("2021-11-14", "2021-11-21", "2021-11-28"),
"V5" = c("2021-12-05", "2021-11-28", "2021-12-12"),
"V6" = c("2021-12-12", "2021-12-19", "2021-12-26"),
"V7" = c("2022-01-02", "2022-01-09", "2022-01-16"),
"V8" = c("2022-01-23", "2022-01-30", "2022-02-06"),
"V9" = c("2022-02-13", "2022-02-20", "2022-02-27"),
"v10" = c("2022-02-27", "2022-03-06", "2022-03-13"))

在所需的输出中,如果任何行单元格(从 V1 列开始)等于相应的“Valid_To”行单元格,则后续单元格(从 V1 列开始)应变为空白

实际 DF 有数百行和列,以及日期格式的 V1 到 VN 列

期望的输出如下:

              df1 <- data.frame(Resource_Code = c("B-T234","B-T234","B- 
T234"),
"Valid_To"= c("2021-10-17", "2021-11-28", "2021-10-31"),
"V1"= c("2021-10-17", "2021-10-17", "2021-10-24"),
"V2" = c("", "2021-10-31", "2021-10-31"),
"V3" = c("", "2021-11-07", ""),
"V4" = c("", "2021-11-21", ""),
"V5" = c("", "2021-11-28", ""),
"V6" = c("", "", ""),
"V7" = c("", "", ""),
"V8" = c("", "", ""),
"V9" = c("", "", ""),
"v10" = c("", "", ""))

我的代码如下:我的代码没有给出所需的输出请帮忙

             for (i in 1:nrow(df1)){
for (j in 3:ncol(df1) ){
if (df[i,j] == df1[1,2]){
df[i,j + 1] <- ""
}

}
}

最佳答案

使用apply的基本R方式。

match 返回 Valid_To 值与 V1V10 列中的日期匹配的位置。如果匹配存在,那么我们将从下一个位置到系列结束的值变为空白。

df[-1] <- t(apply(df[-1], 1, function(x) {
inds <- match(x[1], x[-1])
if(length(inds)) x[(inds + 2):length(x)] <- ''
x
}))
df

# Resource_Code Valid_To V1 V2 V3 V4 V5 V6 V7 V8 V9 v10
#1 B-T234 2021-10-17 2021-10-17
#2 B-T234 2021-11-28 2021-10-17 2021-10-31 2021-11-07 2021-11-21 2021-11-28
#3 B-T234 2021-10-31 2021-10-24 2021-10-31

关于r - 如果满足条件,则在行元素中创建空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69445835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com