Q:

Create vector based on column condition in data frame in R

I have a simple dataframe in the format as follows:
df <- data.frame(var1 = c(1, 1, 1, 2, 2, 2),
                  var2 = c(144, 156, 160, 123, 138, 170))

I want to create a vector (just call it vec) with indexes of the unique values of var1 in my dataframe and then at that index assign the values in var2 that correspond to its value of var1.  So, var1 is the id or grouping variable in my data.  The desired result would look like the following:
vec
"144, 156, 160", "123, 138, 170"
vec[1] 
"144, 156, 160"
vec[2]"123, 138, 170"

A:

We can use split to create a list of vector and then paste it together
var1 <- unname(sapply(split(df$var2, df$var1), toString))
var1[1]
#[1] "144, 156, 160"
var1[2]
#[1] "123, 138, 170"

Or if we need a loop solution
un1 <- unique(df$var1)
out <- character(length(un1))

for(i in seq_along(un1)) out[i] <- toString(df$var2[df$var1 == un1[i]])

out
#[1] "144, 156, 160" "123, 138, 170"

