I have a data frame from an imported CSV in R such as:
Salmon 6
Salmon 4
Salmon 7
Trout 2
Trout 3
Trout 2
that I would like to rearrange to:
Salmon 6 4 7
Trout 2 3 2
The transposed values are each in a new column.
You can use aggregate
:
aggregate(V2 ~ V1, data = mydata, c)
# V1 V2.1 V2.2 V2.3
# 1 Salmon 6 4 7
# 2 Trout 2 3 2
Data:
read.table(text='Salmon 6
Salmon 4
Salmon 7
Trout 2
Trout 3
Trout 2', header=F, quote='"') ->
mydata
Here is an option using dcast
library(data.table)
dcast(setDT(mydata), V1~paste0("VN", rowid(V1)), value.var = 'V2')
# V1 VN1 VN2 VN3
#1: Salmon 6 4 7
#2: Trout 2 3 2
mydata <- structure(list(V1 = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("Salmon",
"Trout"), class = "factor"), V2 = c(6L, 4L, 7L, 2L, 3L, 2L)), .Names = c("V1",
"V2"), class = "data.frame", row.names = c(NA, -6L))