gpt4 book ai didi

r - 来自多个变量的 Pivot_wider 函数(tidyr r 包)

转载 作者:行者123 更新时间:2023-12-05 00:53:38 27 4
gpt4 key购买 nike

我想将数据框放在宽格式中,考虑两个变量作为标准(甚至可能没有必要)。但我对此发表评论是因为原始 df 是 480 行和几个子级别。

这是返回错误!

library(tidyr)
library(dplyr)

df <- structure(list(ID = c(1, 2, 3, 4), Gender = c("Men", "Women", "Men",
"Women"), Country = c("Austria", "Austria", "Austria", "Austria"
), Season_ID = c("2011", "2012", "2011", "2012"), Region_UN = c("A",
"B", "A", "B")), row.names = c(NA,
-4L), class = c("tbl_df", "tbl", "data.frame"))

df_wide <- df %>%
pivot_wider(names_from = Gender,
values_from = Region_UN,
id_cols = c(Country, Season_ID))

警告信息:值不是唯一标识的;输出将包含 list-cols。

  • 使用 values_fn = list 取消此警告。
  • 使用 values_fn = length 确定重复出现的位置
  • 使用 values_fn = {summary_fun} 总结重复项

我不知道我可以在 values_fn 中输入哪个参数!

最佳答案

你也可以粘贴在一起:

df_wide <- df %>%
pivot_wider(names_from = Gender,
values_from = Region_UN,
id_cols = c(Country, Season_ID),
values_fn = function(x) paste(x, collapse=","))

df_wide

因为两者都是一样的:

df_wide <- df %>%
pivot_wider(names_from = Gender,
values_from = Region_UN,
id_cols = c(Country, Season_ID),
values_fn = first)
df_wide

关于r - 来自多个变量的 Pivot_wider 函数(tidyr r 包),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67525049/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com