我有一个 Dataframe (df_old),它有一个变量标签,我想提取标签并将其放入另一个 Dataframe (df_new)的相应变量中。
attr( df_new[ , j] , "label") <- attr( df_old[ , j] , "label")
那不起作用,所以我用这种方法
Tmp <- data.frame( df_old[ , j ] )
names(Tmp) <- "Var"
attr( df_new[ , j] , "label") <- attr( Tmp$Var , "label")
有没有办法一步到位?
UPDATE:包括示例df_old和df_new
df_old <- structure(list(A1_1 = structure(c(1, 3, 2, 1, 6, 1, 5, 7, 1,
1), label = "Use Facebook", format.spss = "F1.0", display_width = 1L, labels = c(`Every day` = 1,
`A few times a week` = 2, `A few times a month` = 3, `Once a month` = 4,
`Every few months` = 5, `Less often` = 6, `I never do this activity` = 7
), class = c("haven_labelled", "vctrs_vctr", "double")), A1_2 = structure(c(1,
4, 1, 7, 7, 1, 1, 7, 1, 6), label = "Use Instagram", format.spss = "F1.0", display_width = 1L, labels = c(`Every day` = 1,
`A few times a week` = 2, `A few times a month` = 3, `Once a month` = 4,
`Every few months` = 5, `Less often` = 6, `I never do this activity` = 7
), class = c("haven_labelled", "vctrs_vctr", "double")), A1_3 = structure(c(1,
1, 2, 7, 7, 6, 1, 7, 2, 1), label = "Use TikTok", format.spss = "F1.0", display_width = 1L, labels = c(`Every day` = 1,
`A few times a week` = 2, `A few times a month` = 3, `Once a month` = 4,
`Every few months` = 5, `Less often` = 6, `I never do this activity` = 7
), class = c("haven_labelled", "vctrs_vctr", "double"))), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"), label = "TvTPQ2_0.sav")
df_new <- data.frame(matrix(0, ncol = ncol(df_old), nrow = nrow(df_old) ))
names(df_new) <- paste0( names(df_old) ,"_new")
2条答案
按热度按时间t1qtbnec1#
您可以使用
for
循环或apply系列函数中的任何一个来传输属性。检查属性-
cs7cruho2#
您可以使用
labelled::var_label()
来提取和指定标签: