0

I have a list/dataframe such as

a b c d e f g VALUE   
1 0 1 0 0 0 1 934

what I wanted to do is to print,

1010001 without using for loop. so basically, take those integers as a string and merge them while printing?

user20650
  • 24,654
  • 5
  • 56
  • 91
MorTunco
  • 19
  • 1
  • 6
  • You want to do that for every row or just for one row? Or your data frame only has one row beyond the titles? Why don't you want to use a for loop? – Bennett Brown Oct 31 '15 at 22:53
  • 1
    if it is a dataframe then `do.call(paste0, dat)` should do it. If not, can you update your question with the results of `dput(head(dat))` please – user20650 Oct 31 '15 at 22:55
  • In this simple case, you dont need a loop: `paste(dataframe[1,1:7],collapse="")` Where dataframe is your dataframe name – maRtin Oct 31 '15 at 22:57
  • 1
    I have to say the immediate downvote seems a bit overzealous ; the op did provide a sample (which could be improved) and expected outcome. – user20650 Oct 31 '15 at 22:58
  • it was my first time asking a question. I will improve my self on later ones. sorry for my bad england – MorTunco Oct 31 '15 at 23:39
  • Hi Tunc, the language in your question is fine. The question would just benefit from displaying your data in a way that it is obvious to others (us) what type of R object it is. http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example is worth a wee read. cheers – user20650 Oct 31 '15 at 23:53
  • what is the `class()` of that object? – Rich Scriven Nov 01 '15 at 00:18

1 Answers1

0

I will define a function, which truncate the last value and paste all the other elements together. And then use "apply" on all the dataframe

cc <- data.frame(a=1,b=0,c=1,d=0,e=0,f=0,g=1,VALUE=934)

# This function contains the all the jobs you want to do for the row.
myfuns <- function(x, collapse=""){
  x <- x[-length(x)] # truncate the last element
  paste(x,collapse="") # paste all the integers together
}

# the second argument "MARGIN=1" means apply this function on the row 
apply(cc,MARGIN=1,myfuns2)   # output: "1010001"
xirururu
  • 5,028
  • 9
  • 35
  • 64
  • OP wanted to do this without using a `for` loop. Your suggestion will be probably even worse. This can be both easily and efficiently solved by just `do.call(paste, c(sep = "", cc[-length(cc)]))` – David Arenburg Nov 01 '15 at 11:40
  • @DavidArenburg Thanks very much for the suggestion. I don't know, what actually happened in `apply`. Do you means, the apply use the `for` loop internal? – xirururu Nov 01 '15 at 22:00
  • 1
    xirururu, yes apply uses a for loop, in r code ... type `apply` into the console to see the function code – user20650 Nov 04 '15 at 03:05