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

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

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

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

似乎是一种奇怪的输出格式,但这里是如何提供代码并(希望)获得答案的示例。

library(dplyr)
library(tidyr)

# 创建示例数据
df <- data.frame(pollinator = c(rep(4, 8), rep(5, 6), rep(6,2)),
                 flower_id = sample(c("H", "L"), 16, replace=TRUE))

# 按组创建唯一标识符
# 转置数据框
# 连接所有列并将其重命名为sequence
# 清理连接的列
df %>%
  group_by(pollinator) %>%
  mutate(n = 1:n(),
         id = paste0(pollinator, flower_id, n)) %>%
  pivot_wider(-n, names_from = id, values_from = flower_id) %>%
  unite(sequence, -pollinator, sep=" ") %>%
  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.

library(dplyr)
library(tidyr)

# create example data 
df &lt;- data.frame(pollinator = c(rep(4, 8), rep(5, 6), rep(6,2)),
                 flower_id = sample(c(&quot;H&quot;, &quot;L&quot;), 16, replace=TRUE))

# create a unique id by group
# transpose the dataframe
# join all the columns and rename it as sequence
# clean up the joined columns
df %&gt;% 
  group_by(pollinator) %&gt;% 
  mutate(n = 1:n(),
         id = paste0(pollinator, flower_id, n)) %&gt;% 
  pivot_wider(-n, names_from = id, values_from = flower_id) %&gt;% 
  unite(sequence, -pollinator, sep=&quot; &quot;) %&gt;% 
  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:

确定