英文:
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?
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.
答案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 <- data.frame(pollinator = c(rep(4, 8), rep(5, 6), rep(6,2)),
flower_id = sample(c("H", "L"), 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 %>%
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)))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论