I have a for loop,& while loop
which produces a data after each iteration.
I want to add all the data together in a data frame but find it difficult. Because only the last data created from the loop is successful(can be seen in the following picture:output code).
Here is the code, please suggest how to fix it:
df = data.frame(matrix(nrow = 350, ncol = 12))
kol<-1
for (x in 1:350) {
output <- c(paste0(x))
df[,1] = output
}
while (kol <= 223) {
if(kol < 224){
rowd1 <- c(paste("gen ",kol))
}
df[,2] = rowd1
kol = kol 1
}#while
while (kol <= 446) {
if(kol < 447){
rowd2 <- c(paste("gen ",kol))
}
df[,3] = rowd2
kol = kol 1
}
colnames(df) <- c("Kromosom", "A","B","C","D","E","F","G","H","I","J","K")
df
so, I will update the question I posed. what if the code becomes like this: the problem: row problem
...
for (x in 1:350) {
output <- c(paste0(x))
df[x,1] = output
}
for (x2 in 1:223) {
output2 <- c(paste("Gen ",x2))
df[1,2:224] = output2
}"#why only the value 223 comes out, like the output in the picture 'row problem' that is -Gen 223-"
...
CodePudding user response:
For a data.frame
df
, df[,n]
is the entire n-th column. So you are setting the entire column at each step. In your code, use
df[x, 1] = output
for example, to set the value for a single row.
CodePudding user response:
SOLVED
Special thanks to @JamesHirschorn, I really appreciate your help in resolving the problem. And thanks to the people who give feedback.
To Do
- would probably stay away from
while
here. Why not just use for instead? – GuedesBF - use
df[x, 1] = output
to set the value for each row in the 1st column
Code
df = data.frame(matrix(nrow = 350, ncol = 224))
for (x in 1:350) {
output <- c(paste(x))
df[x,1] = output
}
for (x2 in 2:224) {
output2 <- c(paste("Gen ",x2-1))
df[1,x2] = output2
}
colnames(df) <- c("Kromosom", "A","B","C","D","E","F","G","H","I","J","K", ...)
df
Output: here .So, wish me luck in the future