I thought many times before posting this, it is really simple but I couldn't find a way to do that, sorry if it is very basic.
I am trying to find a simple command to output a dataframe that includes 2 columns, the value resulting from a for loop, along with the variable name in that loop, here's the command I am using
for (i in 1:length(x)) {
k <- i*5
##### saving the values that comes out of the loop
if (exists("v")== "TRUE" ) {
v= append(v,k)
}
if (exists("v")== "FALSE"){
v <- k
}
###### adding the name of the column
n <- names(x[i])
if (exists("m")== "TRUE" ) {
m= append(m,n)
}
if (exists("m")== "FALSE"){
m <- n
}
}
###### I manually put them into a dataframe and bind them
v <- data.frame(v)
m <- data.frame(m)
df <- cbind(v,m)
the output data frame I am looking for:
v m
5 MUYC
10 KJIO
15 KLGJ
I know this is retarded, the command actually works!! I am sure there are simpler ways to write this! I just couldn't find ones so far.
here's a simple reproducible example
the x matrix
structure(list(MUYC = 1555L, KJIO = 320L, KLGJ = 5132L), .Names = c("MUYC",
"KJIO", "KLGJ"), class = "data.frame", row.names = c(NA, -1L))
Many thanks,