1

I want to print the output as a one line for each variable dd and vv

df=c(1:20)
df=matrix(df,ncol = 5,nrow = 4, byrow = T)
x=c(1.5,7.5,12.5,19.5)
for (j in 1:4) {
  for (i in 1:4) {
    if( sum(df[j,i],df[j,i+1])/2 ==x[j])
    {xx=c(df[j,i],df[j,i+1]) }
  }
  dd=as.vector((df[j,i+1]-df[j,i])/6)
  vv=as.vector(xx)
  print(c(vv,dd))
}

I got the following

  [1] 1.0000000 2.0000000 0.1666667
  [1] 7.0000000 8.0000000 0.1666667
  [1] 12.0000000 13.0000000  0.1666667
  [1] 19.0000000 20.0000000  0.1666667

and what I want to print from my code is

[1]  1  2  7  8 12 13 19 20

and

[1]0.1666667 0.1666667 0.1666667 0.1666667

3 Answers 3

2

Here's a way by storing the results in a vector:

# store the results
dd_var = c()
vv_var = c()

for (j in 1:4) {
  for (i in 1:4) {
    if( sum(df[j,i],df[j,i+1])/2 ==x[j])
    {xx=c(df[j,i],df[j,i+1]) }
  }

  dd=as.vector((df[j,i+1]-df[j,i])/6)
  vv=as.vector(xx)
  dd_var = append(dd_var, dd)
  vv_var = append(vv_var, vv)
}

cat(dd_var,'\t')
0.1666667 0.1666667 0.1666667 0.1666667 

cat(vv_var, '\t')
1 2 7 8 12 13 19 20
Sign up to request clarification or add additional context in comments.

Comments

1

The situation here is that the print statement is inside of the for loop and did not store your results as a vector that appends all the answers (instead, your code stores each result as a unique variable for each iteration). I see the previous answers, but here is my modification which is very similar to your original.

1) Added two NULL vectors, dd and vv

2) Stored each looped result into the respective vectors

3) Print statement outside of the for loop

dd <- NULL
vv <- NULL


df=c(1:20)
df=matrix(df,ncol = 5,nrow = 4, byrow = T)
x=c(1.5,7.5,12.5,19.5)
for (j in 1:4) {
  for (i in 1:4) {
    if( sum(df[j,i],df[j,i+1])/2 ==x[j])
    {xx=c(df[j,i],df[j,i+1]) }
  }
  dd <- as.vector(c(dd,(df[j,i+1]-df[j,i])/6))
  vv <- as.vector(c(vv,(xx)))
}

print(dd)
print(vv)

Comments

0

Pretty similar what @YOLO came up with... Store the result into an object and print it using cat. There are other ways of going about this.

dd.out <- c()
vv.out <- c()

for (j in 1:4) {
  for (i in 1:4) {
    if( sum(df[j,i],df[j,i+1])/2 ==x[j])
    {xx=c(df[j,i],df[j,i+1]) }
  }

  dd=as.vector((df[j,i+1]-df[j,i])/6)
  vv=as.vector(xx)

  # Growing an object is not optimal, but works.
  dd.out <- c(dd.out, dd)
  vv.out <- c(vv.out, vv)
}
cat(vv.out, "\n", dd.out)

1 2 7 8 12 13 19 20 
 0.1666667 0.1666667 0.1666667 0.1666667

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.