【问题标题】:How do I reshape this data frame with R? [duplicate]如何用 R 重塑这个数据框? [复制]
【发布时间】:2021-08-09 13:07:49
【问题描述】:

我是 R 新手,需要一些帮助来重塑与以下类似的数据框:

company_name year profit_usd profit_eur profit_gbp
A 2017 1237 1006 871
B 2017 1337 1096 949
A 2018 1143 937 811
B 2018 1288 1056 914

我想重塑这个表格,使我只有一列显示利润,另一列显示货币名称。像这样的:

company_name year currency profit
A 2017 usd 1237
A 2017 eur 1006
A 2017 gbp 871
B 2017 usd 1337
B 2017 eur 1096
B 2017 gbp 949
A 2018 usd 1143
A 2018 eur 937
A 2018 gbp 811
B 2018 usd 1288
B 2018 eur 1056
B 2018 gbp 914

我们将不胜感激任何帮助,谢谢!

【问题讨论】:

  • 如果您提供的数据不是表格,那将很有帮助,例如通过使用dput(YOURDATA) 或者,如果数据太大dput(head(YOURDATA))。另外:stackoverflow.com/help/minimal-reproducible-example
  • @deschen 感谢您的提示 - 我会在以后的问题中记住这一点
  • @zx8754:我投票赞成重新提出这个问题。您链接的这篇文章并非可以回答有关重塑主题的每个问题。 IE。在这种特殊情况下,我们可以充分利用pivot_longer 中的names_sep 参数,这在您链接的帖子中不是一个可行的选项。
  • 我同意这不在它所标记的帖子中,但这绝对是以前发布过的问题。 Thisthis 似乎是更好的目标。 @zx8754 你想添加其中任何一个吗?
  • @camille 感谢您提供的链接,已更新。

标签: r reshape


【解决方案1】:

假设您的数据存储在对象df

library(tidyverse)

df %>%
  pivot_longer(cols      = starts_with("profit"),
               names_sep = "_",
               names_to  = c("delete", "currency"),
               values_to = "profit") %>%
  select(-delete)

【讨论】:

  • 行得通,谢谢!
  • 随意将其(或您认为有帮助的任何其他答案)标记为您接受的答案,以便其他人可以从中受益。
【解决方案2】:

除了deschen的回答。

library(tidyr)

#long format
df <- pivot_longer(df, cols = c("profit_usd", "profit_eur", "profit_gbp"), names_to = "currency", values_to = "profit")

#removes profit_ from your currency column
df$currency <- gsub("profit_", "", df$currency)

我个人偏好不使用管道函数。尤其是刚开始时,使用管道函数会创建长代码行,与多行代码相比,这些代码行更难调试。管道函数的优点当然是代码更短。

【讨论】:

  • 感谢您的回答和提示 - 我会牢记这一点!
猜你喜欢
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 2010-12-04
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
相关资源
最近更新 更多