I have a df with 56 rows, and I want to update var PAV" base on
tt`. It is very simple but I got very strange errors. Could anyone tell me what might be the reason?
df<-structure(list(tt = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Y", "Y", "Y", "Y", "Y",
"Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y",
"Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y",
"Y", "Y", "Y", "Y", "Y"), PAV = structure(c("2", "2", "2", "2",
"2", "2", "3", "3", "3", "3", "3", "3", "3", "3", "3", "3", "3",
"3", "5", "5", "4", "4", "4", "4", "4", "4", "4", "4", "4", "4",
"4", "4", "4", "4", "4", "4", "4", "4", "4", "4", "4", "4", "4",
"4", "4", "4", "7", "7", "7", "7", "7", "7", "7", "7", "7", "7",
"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", ""), .Dim = c(56L,
2L))), class = "data.frame", row.names = c(NA, 56L))
df<- df %>%
mutate(PAV=case_when(tt=="Y"~PAV))
The error code is: Error: Problem with
mutate()column
PAV. i
PAV = case_when(tt == "Y" ~ PAV). x
tt == "Y" ~ PAV must be length 56 or one, not 112.
CodePudding user response:
The column 'PAV' is a matrix
column. We may need to convert to two regular columns first and then loop across
those columns to update the values
library(purrr)
library(dplyr)
df %>%
invoke(data.frame, .) %>%
mutate(across(starts_with('PAV'), ~ case_when(tt %in% 'Y' ~ .x)))