Reputation: 13
I'm trying to merge several hundred columns of a dataframe. Currently trying to do this with a for loop, which isn't working.
The columns are numbered 1 : n, lets say 512.
for(i in 1:512) {
DF[as.numeric(i)] <-paste(DF[as.numeric(i)], DF[as.numeric(i)+1])
}
(using the "as.numeric(i)" since I was getting errors when trying to select the next column)
EDIT
All the values are strings, with many rows not being filled till the 512 columns. I'm trying to combine all the strings in 1 row into a single string.
Upvotes: 1
Views: 202
Reputation: 20085
You can try apply
with paste0
as:
df <- data.frame(id = 1:10, name = rep(c("Test1", "Test2"),5),
value = 101:110, stringsAsFactors = FALSE)
apply(df, 1, paste0, collapse ="")
#Result
# [1] " 1Test1101" " 2Test2102" " 3Test1103" " 4Test2104" " 5Test1105" " 6Test2106"
# [7] " 7Test1107" " 8Test2108" " 9Test1109" "10Test2110"
Upvotes: 1