如果与另一列中的值匹配,则用'空白'替换该列中的值[重复]

问题描述 投票:0回答:1

我有以下数据集作为R中的数据帧

article_number   1st_cutoff_date   2nd_cutoff_date

abc                12/01/2019       01/14/2020

def                02/10/2020       02/10/2020

[我想做的是在1st_cutoff_date == 2nd_cutoff_date的情况下,然后将2nd_cutoff日期替换为空白值“”。因此,在第二种情况下,'def'则2nd_cutoff_date将为空“”

数据帧是有因素的,有NA-我已转换为字符并尝试了以下操作:

AAR_FTW_Final_w_LL[AAR_FTW_Final_w_LL$`1st_Booking_Deadline` == AAR_FTW_Final_w_LL$`2nd_Booking_Deadline`, c("2nd_Booking_Deadline")] <- " "

ind<- AAR_FTW_Final_w_LL$`1st_Booking_Deadline` == AAR_FTW_Final_w_LL[`2nd_Booking_Deadlilne`]
AAR_FTW_Final_w_LL[ind, c("2nd_Booking_Deadline")] <- " "

均返回错误:

Error in AAR_FTW_Final_w_LL$`1st_Booking_Deadline` : 
  $ operator is invalid for atomic vectors

我曾尝试用[]替换$,但随后出现以下错误:缺少一列。有没有更简单的方法可以执行此任务?

r match na
1个回答
1
投票
从因子转换为字符:

df[] <- lapply(df, as.character)

然后使用replace

transform(df, `2nd_cutoff_date` = replace(`2nd_cutoff_date`, `1st_cutoff_date` == `2nd_cutoff_date`, '')) # article_number X1st_cutoff_date X2nd_cutoff_date #1 abc 12/01/2019 01/14/2020 #2 def 02/10/2020

X添加到列名,因为R在列中以数字开头不是标准。 


将数据转换为字符后的另一种方法是

df$`2nd_cutoff_date`[df$`1st_cutoff_date` == df$`2nd_cutoff_date`] <- ""

数据

df <- structure(list(article_number = structure(1:2, .Label = c("abc", "def"), class = "factor"), `1st_cutoff_date` = structure(2:1, .Label = c("02/10/2020", "12/01/2019"), class = "factor"), `2nd_cutoff_date` = structure(1:2, .Label = c("01/14/2020", "02/10/2020"), class = "factor")), class = "data.frame", row.names = c(NA, -2L))
© www.soinside.com 2019 - 2024. All rights reserved.