-2

i have problem when im want to assign value from looping to dataframe

im try with the code :

output1 <- data.frame(matrix(ncol=1, nrow=10))
colnames(output1) <- "id"
for(i in seq(from=1, to=10, by=1)){
 for(j in seq(from=1, to=2, by=1)){
    output[i,] <- i
    print(paste(i))
  }
}

enter image description here

and if view print(i) the result is :

"1"
"1"
"2"
"2"

and actual result in dataframe is

id : "1","2","3"--"10"

enter image description here

please help me, thank you

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Rizka Rahayu
  • 81
  • 10

2 Answers2

0

Why are you looping again inside? for(i in seq(from=1, to=10, by=1)){ i will be a straight sequence from 1 to 10 for(j in seq(from=1, to=2, by=1)){ j will only assume either 1 or 2 so:

if i=1 enters the first loop and j=1 the output[1,] <- 1 now j=2 and output[1,] <- 1

if what you want is to repeat the first value, your second assign should be the j value, something like this

output1 <- data.frame(matrix(ncol=1, nrow=10))
 colnames(output1) <- "id"
 for(i in seq(from=1, to=10, by=2)){
  for(j in seq(from=1, to=2, by=1)){
    output[i,] <- i
    output[i+1,] <- j
    print(paste(i))
  }
}

There are also better ways to achive your result (if repeating the value is your desired result)

output1 <- data.frame(matrix(ncol=1, nrow=10))
 colnames(output1) <- "id"
 for(i in seq(from=1, to=10, by=2)){
    output[i,] <- i
    output[i+1,] <- i+1
    print(paste(i))
}

you can also refer to this question Sequence of Repeated Values in R

which will basically tell you you can create a vector of repeated values in a sequence by using the rep() command in R

0

If what you are trying to do is add each part of the first sequence to your data frame twice, you need to do something else. Your second loop only sets the i-th number to the i-th position twice. What you want to do is set the i-th number to the 2*i-th and 2*i+1-th position, I guess?

Therefore aaron parrillas code is correct, if you adjust it a little:

output <- data.frame(matrix(ncol=1, nrow=20))
colnames(output) <- "id"
for(i in seq(from=1, to=10, by=1)){
  output[(2*i)-1,] <- i
  output[(2*i),] <- i
  print(paste(i))
}

Is this what you are looking for?

pandayo
  • 310
  • 2
  • 13