[R] For loop and using its index
chuck.01
CharlieTheBrown77 at gmail.com
Fri Mar 9 19:36:48 CET 2012
Hassan,
Others have provided you with better solutions, but I hope this allows you
to see why yours didn't work.
# first (going with your code) you needed a data.frame called "x"
# here is an example:
x <- structure(list(x1 = c(0.0986048226696643, -0.445652024980979,
0.0893989676314604, -3.02656448303247, -0.966125836458264,
-1.49916656636977,
-1.43173455089552, 0.370528111260298, -1.16980816517156, -0.808744946153693
), x2 = c(-0.765406771195136, -0.37933377428095, 1.38846324586498,
-1.70043724374807, -0.71331175577977, 1.44597103991061, 1.31674350467787,
-0.954578441470943, -1.30637013925954, 0.551870274117374), x3 =
c(-0.122350075070145,
1.6217818199546, -0.824570718637696, -0.0341988842898353, 1.03924814479596,
0.898533448980663, 0.68074228601446, 0.296251937506574, -0.698501590358135,
-0.0533564535030227)), .Names = c("x1", "x2", "x3"), row.names = c(NA,
-10L), class = "data.frame")
# you then need an empty vector to hold the results of your for loop (called
"z" here)
# note the square brackets as opposed to your parentheses
z <- vector("list")
for (i in 1:ncol(x)) {
z[i] = 200 - x[i]
}
# finally, this will reassemble the output of the for loop
z <- do.call(cbind, z)
colnames(z) <- c("z1", "z2", "z3")
# Finally, do read what the others sent you as they provide more efficient
solutions
HTH
Chuck
Hassan Eini Zinab wrote
>
> Dear All,
>
> I have a data set with variables x1, x2, x3, ..., x20 and I want to
> create z1, z2, z3, ..., z20 with the following formula:
>
>
> z1 = 200 - x1
> z2 = 200 - x2
> z3 = 200 - x3
> .
> .
> .
> z20 = 200 - x20.
>
>
> I tried using a for loop and its index as:
>
> for (i in 1:20) {
> z(i) = 200 - x(i)
> }
>
> But R gives the following error message: "Error: could not find function
> "x"".
>
> Is there any other way for a simple coding of my 20 lines of code?
>
> Alohas,
> Hassan Eini-Zinab
>
> ______________________________________________
> R-help@ mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
View this message in context: http://r.789695.n4.nabble.com/For-loop-and-using-its-index-tp4459454p4460277.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list