I have a data frame with many columns and I would like to combine columns started from column 5. I try to use apply to do this.
Data Frame:
1 682333 191.858 191517119 C A C A A A C A A A A A
2 1862626 71.9275 56032940 A C C C A A A C A C A A
3 11957134 155.78 150230950 B B B B A B A B A B A B
4 2516482 51.2692 31496569 B A A A A A A A A A A A
5 9378200 51.2798 31572927 A A B B B A A A A A B A
6 2071534 52.1573 32824318 A B A B A B A B B B A B
7 2074633 33.068 19035920 A A B A A A B A B A B A
8 7856856 121.811 117540910 A A A A A A A A B A B A
9 3741206 2.18574 2169864 A A A A A A A A A A A A
10 4411364 12.5959 24191374 C C A C A C C C A C A C
Output:
1 682333 191.858 191517119 CA CA AA CA AA AA
2 1862626 71.9275 56032940 AC CC AA AC AC AA
3 11957134 155.78 150230950 BB BB AB AB AB AB
4 2516482 51.2692 31496569 BA AA AA AA AA AA
5 9378200 51.2798 31572927 AA BB BA AA AA BA
6 2071534 52.1573 32824318 AB AB AB AB BB AB
7 2074633 33.068 19035920 AA BA AA BA BA BA
8 7856856 121.811 117540910 AA AA AA AA BA BA
9 3741206 2.18574 2169864 AA AA AA AA AA AA
10 4411364 12.5959 24191374 CC AC AC CC AC AC
I tried like this:
col <- apply(df[,-1:-4], 2, function(x) {paste(x,x+1,sep="")}
df <- cbind(df[,1:4],col)
But there is an error:
Error in x + 1 : non-numeric argument to binary operator.
You can use Map to loop through odd position columns and even position columns in parallel and paste corresponding column together:
as.data.frame(c(df[1:4], Map(function(x, y) paste(x, y, sep = ""),
df[-(1:4)][c(TRUE, FALSE)], # use cycling rule to pick
# odd position columns
df[-(1:4)][c(FALSE, TRUE)]))) # pick even position columns
# V1 V2 V3 V4 V5 V7 V9 V11 V13 V15
#1 1 682333 191.85800 191517119 CA CA AA CA AA AA
#2 2 1862626 71.92750 56032940 AC CC AA AC AC AA
#3 3 11957134 155.78000 150230950 BB BB AB AB AB AB
#4 4 2516482 51.26920 31496569 BA AA AA AA AA AA
#5 5 9378200 51.27980 31572927 AA BB BA AA AA BA
#6 6 2071534 52.15730 32824318 AB AB AB AB BB AB
#7 7 2074633 33.06800 19035920 AA BA AA BA BA BA
#8 8 7856856 121.81100 117540910 AA AA AA AA BA BA
#9 9 3741206 2.18574 2169864 AA AA AA AA AA AA
#10 10 4411364 12.59590 24191374 CC AC AC CC AC AC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With