-2

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?

Image 1

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.

Image 2

M--
  • 25,431
  • 8
  • 61
  • 93
  • 5
    Welcome to Stack Overflow. We cannot read data into R from images. Please [make this question reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) by including a small representative dataset in a plain text format - for example the output from `dput(yourdata)`, if that is not too large. – neilfws May 22 '23 at 04:05
  • Please provide enough code so others can better understand or reproduce the problem. – Community May 22 '23 at 16:30

1 Answers1

0

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)))
B Williams
  • 1,992
  • 12
  • 19
  • Hi @B Williams. Thank you so much for the answer. Actually, I don't want to unite the columns. Is there any way to remove NAs without uniting the columns? – Saket Shrotri May 23 '23 at 05:41
  • Basically I want the output to be in the following: data <- data.frame( pollinator = c(4, 5), sequence = list( c("H", "L", "L", "H", "L", "H", "L", "H"), c("L", "H", "L", "L", "L", "H"), ) ) – Saket Shrotri May 23 '23 at 07:17