mmarion
February 22, 2023, 2:00am
1
Desired output: 2 columns
predictors mycor
x1 -0.077
x2 -0.266
x3 0.086
x4 -0.037
x5 -0.201
x6 0.055
x7 -0.041
x8 -0.306
x9 0.020
x10 0.038
x11 0.444
11 rows
The following code runs just fine if mycor is entered in manually. But if I try to use mycor created within the loop for(in in 1:11) only the last entry .444 is output. See r code below. cbind and data.frame commands are both giving similar results.
Output:
predictors mycor
x1 0.444
x2 0.444
x3 0.444
x4 0.444
x5 0.444
x6 0.444
x7 0.444
x8 0.444
x9 0.444
x10 0.444
x11 0.444
11 rows
for(i in 1:11){
v <- paste("x",i,sep="")
v2 <- i
mycor <- round(cor(df2[[v]], df2$y2),3)
}
predictors <- c( "x1","x2","x3","x4","x5","x6","x7","x8","x9","x10","x11")
mycor <- c(-0.077,-0.266, 0.086,-0.037,-0.201,0.055,-0.041,-0.306,0.020,0.038, 0.444)
corSummary <- cbind(predictors,mycor)
corSummary
data.frame(predictors,mycor)
What is happening here?
What happens in Vegas, stays in Vegas, and what happens in functions, including loops, stays in the function’s .Local
environment unless explicitly sent to the .Global
environment.
There are a few different ways to do this:
Assignment
result <- some_function()
return()
Assignment within function
holder <- vector(length = 16)
for(i in 1:15) holder[i] = i^2
mmarion
February 23, 2023, 3:16pm
3
[quote="technocrat, post:2, topic:160513"]
There are a few different ways to do this:
Assignment
result <- some_function()
return()
Assignment within function
holder <- vector(length = 16)
for(i in 1:15) holder[i] = i^2
With a little perserverance, I succeeded.
df$quality3 <- vector(length=6497)
for(i in 1:6497){
df$quality3[i] = 1
if(df$quality[i] == 6 )
{df$quality3[i]=2}
if(df$quality[i]== 7)
{df$quality3[i]=2}
if(df$quality[i] >= 8)
{df$quality3[i]=3}
}
y3 <- df$quality3
Thank you.
MM
1 Like
system
Closed
April 6, 2023, 3:17pm
4
This topic was automatically closed 42 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.