My df
df = structure(list(record_id = c("8472", "6648"),
ne_nombre = c("John",
"Peter"),
ne_cc = c("1234", "5678"),
ne_idatencion = c(1111, 2222),
nom_ips = structure(1:2,
redcapLabels = c("Store 1",
"Store 2"),
redcapLevels = 1:2),
ev_faudit = c("2022-04-27 09:48",
"2022-04-27 12:49"),
ev_nomusuar = c("jane", "joe"),
ev_obs2 = c("pending",
"pending")
),
row.names = c(NA, -2L), class = c("tbl_df", "tbl",
"data.frame"))
The field df$nom_ips
is a numeric type field which includes attribute data. I require to replace its numeric field with its associated label so df$nom_ips
ends up being Store 1 Store 2
I have tried this with no luck :
. <- attr(df11$nom_ips, "redcapLabels")
df11$nom_ips1 <- factor(df11$nom_ips, ., names(.))
Error in factor(df11$nom_ips, ., names(.)) :
invalid 'labels'; length 0 should be 1 or 2
CodePudding user response:
Specify the argument name
df11$nom_ips1 <- factor(df11$nom_ips, levels = attr(df11$nom_ips,"redcapLevels"),
labels = attr(df11$nom_ips, "redcapLabels"))
-output
> df11$nom_ips1
[1] Store 1 Store 2
Levels: Store 1 Store 2
Or use do.call
after changing the attribute
names with labels
and levels
do.call(factor, c(list(df11$nom_ips),
setNames(attributes(df11$nom_ips), c("labels", "levels"))))
[1] Store 1 Store 2
Levels: Store 1 Store 2