Reputation:
My dataframe contains the following:
data$Value data$Name
774 Name1
770 Name1
778 Name1
804 Name1
804 Name1
802 Name1
804 Name1
900 Name2
905 Name2
805 Name2
900 Name2
950 Name2
860 Name2
870 Name2
etc... etc... for 100 Names
So, each Name has 7 Values associated to it. I would like to group this data frame by variable "Name", split it and returning the 7 values for each of those names as a list. This is the format of my desired output:
my_list$Name1 =
[[1]]
[1] 774 770 778 804 804 802 804
my_list$Name2 =
[[1]]
[1] 900, 905, 805, 900, 950, 860, 870
etc...
The easiest solution is to use plyr's dlply
function:
my_list <- dlply(data, "Name", function(x) list(x$Value))
However, I would like to avoid using plyr. What would be a good alternative? I have considered splitting my data the following way:
splits <- function(x) {
y <- subset(data, select = c(Name, Value))
splits <- split(y, y$Name)
return(splits)
}
my_list <- splits(data)
However, this still returns me a list in the following format:
Value Name
(dbl) (chr)
1 774 Name1
2 770 Name1
3 778 Name1
4 804 Name1
5 804 Name1
6 802 Name1
7 804 Name1
UPDATE: SOLUTION:
my_list <- lapply(split(data$Value, data$Name), list)
Upvotes: 4
Views: 915
Reputation: 51592
One way to do it,
y <- subset(data, select = c(Name, Value))
list <- split(y, y$Name)
unlist(sapply(list, '[', 1))
or
unlist(unname(sapply(list, '[', 1)))
or simply (compliments of @docendo discimus)
unlist(unname(split(y$Value, y$Name)))
Regarding your comment, then you can do,
unname(split(y$Value, y$Name))
#[[1]]
#[1] 774 770 778 804 804 802 804
#[[2]]
#[1] 900 905 805 900 950 860 870
Upvotes: 3