I have a dataframe like this:
set.seed(123)
df <- data.frame(v1 = sample(1:4, 100, replace = T),
v2 = sample(1:4, 100, replace = T),
v3 = sample(1:4, 100, replace = T),
v4 = sample(1:4, 100, replace = T),
v5 = sample(1:4, 100, replace = T))
and I want to paste together rolling pairs of columns: v1and v2, v2and v3, v3 and v4, and so on. I tried doing this with apply within a for loop:
pairs <- c()
for(i in 1:ncol(df)){
pairs <- apply(df[,c(i,i+1)], 1, paste0, collapse = "-")
}
but this throws an error:
Error in `[.data.frame`(df, , c(i, i + 1)) : undefined columns selected
What's wrong with the loop? And how could the pairing be achieved?