如何在R中自动执行转置?

huangapple go评论93阅读模式
英文:

How to automate transpose in R?

问题

我有多个传粉者的顺序访问数据(见图1)。为了分析花卉恒定性数据,我想根据传粉者ID对它们进行转置(见图2)。有办法在R中自动化这个过程吗?

英文:

I have a data of sequential visits of multiple pollinators in long form (see image 1). In order to analyse the floral constancy data, I want to transpose them according to pollinator_ID (see image 2). Is there any way to automate this in R?

如何在R中自动执行转置?

I have tried converting the data into wide format, but from there I am not sure how to proceed. Here is the Image 2 which is what I expect the output to be.

如何在R中自动执行转置?

答案1

得分: 0

以下是您提供的代码的翻译:

  1. 似乎是一种奇怪的输出格式,但这里是如何提供代码并(希望)获得答案的示例。
  2. library(dplyr)
  3. library(tidyr)
  4. # 创建示例数据
  5. df <- data.frame(pollinator = c(rep(4, 8), rep(5, 6), rep(6,2)),
  6. flower_id = sample(c("H", "L"), 16, replace=TRUE))
  7. # 按组创建唯一标识符
  8. # 转置数据框
  9. # 连接所有列并将其重命名为sequence
  10. # 清理连接的列
  11. df %>%
  12. group_by(pollinator) %>%
  13. mutate(n = 1:n(),
  14. id = paste0(pollinator, flower_id, n)) %>%
  15. pivot_wider(-n, names_from = id, values_from = flower_id) %>%
  16. unite(sequence, -pollinator, sep=" ") %>%
  17. mutate(sequence = trimws(gsub("NA", "", sequence)))

请注意,代码中的HTML实体已被还原为正常文本。

英文:

Seems an odd output format, but here is an example of how you can provide code and (hopefully) get an answer.

  1. library(dplyr)
  2. library(tidyr)
  3. # create example data
  4. df &lt;- data.frame(pollinator = c(rep(4, 8), rep(5, 6), rep(6,2)),
  5. flower_id = sample(c(&quot;H&quot;, &quot;L&quot;), 16, replace=TRUE))
  6. # create a unique id by group
  7. # transpose the dataframe
  8. # join all the columns and rename it as sequence
  9. # clean up the joined columns
  10. df %&gt;%
  11. group_by(pollinator) %&gt;%
  12. mutate(n = 1:n(),
  13. id = paste0(pollinator, flower_id, n)) %&gt;%
  14. pivot_wider(-n, names_from = id, values_from = flower_id) %&gt;%
  15. unite(sequence, -pollinator, sep=&quot; &quot;) %&gt;%
  16. mutate(sequence = trimws(gsub(&quot;NA&quot;, &quot;&quot;, sequence)))

huangapple
  • 本文由 发表于 2023年5月22日 12:04:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定