1

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"
1
  • Don't you need aggregate(var2~var1, df, toString) ? The second column is vec. Commented Apr 2, 2020 at 2:41

1 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

1 Comment

that works...anyone have a loop solution for reference??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.