昨天,当我试图使用mutate()函数在特定列中重新编码一些值时,一切都很好。但是突然之间,我今天再次运行这些代码,它返回了mutate()函数行中的错误:
Can't transform a data frame with duplicate names.回溯:
-1))
这是我昨天用得很好的代码
#recode the 1 in column C001 to be 5, 2 to be 4#
EVS_recode <- EVS_recode %>% mutate(C001= recode(C001, '1' = 5, '2'= 4))
#recode the -1,-2,-4,-5 values to be NA in column C001#
EVS_recode <- EVS_recode %>% mutate_at(c('C001'), ~na_if(.,-1))
EVS_recode <- EVS_recode %>% mutate_at(c('C001'), ~na_if(.,-2))
EVS_recode <- EVS_recode %>% mutate_at(c('C001'), ~na_if(.,-4))
EVS_recode <- EVS_recode %>% mutate_at(c('C001'), ~na_if(.,-5))这是我第一次拥有如此大规模的与mutate()无关的代码。在使用mutate()时,有人能帮助我或者有类似的问题吗?
感谢您有时间阅读这个!如果有人能给我个提示会很有帮助的。
发布于 2022-09-19 07:51:04
在dataframe中不能有两个同名的变量,因此出现了错误。
您可以尝试一次使用case_when()来实现这一点,也许它解决了错误。
library(dplyr)
df <- tibble::tibble(C001 = c(-1,1,-2,3, -4, -5, 5,5,3,2,1,-1))
df %>%
mutate(across(C001, ~ case_when(
C001 == 1 ~ 5,
C001 == 2 ~ 4,
C001 %in% c(-1, -2, -4,-5) ~ NA_real_,
TRUE ~ C001
)))您也可以使用replace
df %>% mutate(across(C001, ~replace(., . %in% c(-1, -2, -4,-5), NA)))https://stackoverflow.com/questions/73769850
复制相似问题