[R] Script/function/procedure with loop

Sarah Goslee sarah.goslee at gmail.com
Mon Jul 11 22:43:31 CEST 2016


Taking your question at face value, except for the factors in your
original data frame, you can output anything you'd like to text
onscreen using cat(). Output can also be saved to text files with
sink() or using batch files, etc and so forth.



date <- c("07-jul-16","07-jul-16","07-jul-16","08-jul-16","08-jul-16","08-jul-16","09-jul-16","09-jul-16")
varA <- c("text A1","text A2","text A3","text A4","text A5","text
A6","text A7","text A8")
varB <- c("link B1","link B2","link B3","link B4","link B5","link
B6","link B7","link B8")
mydf <- data.frame(date, varA, varB, stringsAsFactors=FALSE)

for(i in sort(unique(mydf$date))) {
  thisdate <- subset(mydf, date==i)
  cat(i, "\n\n")
  for(j in seq_len(nrow(thisdate))) {
    cat(thisdate$varA[j], "\n")
    cat(thisdate$varB[j], "\n\n")
 }
}

This code prints to screen:

07-jul-16

text A1
link B1

text A2
link B2

text A3
link B3

08-jul-16

text A4
link B4

text A5
link B5

text A6
link B6

09-jul-16

text A7
link B7

text A8
link B8


On Mon, Jul 11, 2016 at 4:24 PM, Luca Meyer <lucam1968 at gmail.com> wrote:
> Can anyone point me to an R script/function/procedure which, starting from
> the following sample data
>
> #sample data
> #NB: nrow(df) is variable
>
> date =
> c("07-jul-16","07-jul-16","07-jul-16","08-jul-16","08-jul-16","08-jul-16","09-jul-16","09-jul-16")
> varA = c("text A1","text A2","text A3","text A4","text A5","text A6","text
> A7","text A8")
> varB = c("link B1","link B2","link B3","link B4","link B5","link B6","link
> B7","link B8")
> df = data.frame(date, varA, varB)
>
> allows me to obtain a text output such as:
>
>> 07-jul-16
>
> text A1
> link B1
>
> text A2
> link B2
>
> text A3
> link B3
>
>> 08-jul-16
>
> text A4
> link B4
>
> text A5
> link B5
>
> text A6
> link B6
>
>> 09-jul-16
>
> text A7
> link B7
>
> text A8
> link B8
>
> etc...
>
> Thanks,
>
> Luca
>
>         [[alternative HTML version deleted]]

Please post in plain text.

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list