Make output of two rows into columns R

48 views Asked by At

I am currently working with behavioural data in R from video analyses in BORIS. Every observation is 15 seconds and during this observation I noted the subject, its behaviour but also some background information such as the date, time of day, temperature, etc. However, the program has put this background information under the column "Behaviour" (so one of the behaviours is now "date") and its output under the column "Modifier" (which now says "15-10-2020" for example).

What I want is make more columns of date, time etc (from the column "Behaviour") and put its output (from the column "Modifier") in these columns, so that every behaviour has a subject, date, time, temperature, and so forth. I have however no idea how to do this.

I thought about using the function aggregate, but this gives me lots of extra rows with mainly NA's. I also looked into the package "tibble" but can't really make that work either.

Any suggestions would be greatly appreciated!

Some example rows (from dput()):

structure(list(Subject = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 7L), .Label = c("fallow deer female", "fallow deer female + calf", 
"red deer female + calf", "roe deer male", "wild boar + young", 
"wild boar male", "wild boar unknown sex"), class = "factor"), 
    Behavior = structure(c(1L, 2L, 8L, 7L, 12L, 3L, 5L, 10L, 
    6L, 4L), .Label = c("auditory vigilant", "date", "day/night", 
    "foraging", "nr. of individuals", "running", "temperature", 
    "time of day", "unknown behaviour", "walking", "walking while vigilant", 
    "weather"), class = "factor"), Behavioral.category = structure(c(4L, 
    2L, 2L, 2L, 2L, 2L, 2L, 3L, 4L, 3L), .Label = c("", "Background information", 
    "Non-vigilant", "Vigilant"), class = "factor"), Modifiers = structure(c(1L, 
    4L, 21L, 27L, 35L, 36L, 32L, 1L, 1L, 1L), .Label = c("", 
    "0346", "0347", "07172020", "07182020", "07212020", "07242020", 
    "07262020", "07272020", "08032020", "08052020", "1", "12", 
    "1307", "1327", "1342", "1343", "1430", "1528", "16", "1604", 
    "17", "1744", "21", "2119", "2120", "22", "23", "25", "26", 
    "3", "4", "7", "Clear", "Cloudy", "Day", "Night"), class = "factor")), row.names = c(NA, 
10L), class = "data.frame")

The output that I'd like to have would give as column names: Subject; Behavior; Date; Time of Day; Temperature. The modifier output would be the values of the columns "Date", "Time of Day", "Temperature". When this works, I could delete the column Modifiers (since all its values are already in assigned columns).

1

There are 1 answers

0
Josefien On BEST ANSWER

Split up the dataframe in actual behaviours and background information. Perform this code on the background information:

tidyr::pivot_wider(your_data, names_from = Behavior, values_from = Modifiers)

Merge the dataframes!