Skip to content
Prev 316722 / 398506 Next

Why replacement has length zero? And How can I fix it?

Hi:

No offense, but this is code is inefficient on several levels.
Firstly, a loop is unnecessary (see below); secondly,  ifelse() is a
vectorized function and you're attempting to apply it to each row of
DataSet. Try this instead, given

 dput(DataSet)
structure(list(Age = c(-0.552450789929175, -2.06988485889524,
-1.1290497440272, -0.268777167923272, -0.012748181465016, 0.554761979685086,
0.179401201802416, 0.0973216900180107, -0.914782595075178, -1.53708818506571
), Gender = c(-0.0705367578252014, 0.969426004829301, 0.0556317051882303,
1.33716753655214, -0.638382962845772, 0.480939398350137, -0.755053441639217,
1.25393329162734, 1.45933385954704, 0.672871276697159), SES =
c(-1.88102131807556,
0.529181612783923, 0.271835979074789, -0.656415898217512, -0.517622943602359,
0.639094817790355, -1.08205962796926, -0.193116856300625, 0.707374091321319,
1.98180909069287), ISS = c(-1.74208565286036, -1.235721877648,
0.459828219284939, -0.87781916182417, -0.429262433047679, 0.379335629940134,
0.949088546564315, 0.689758637278236, -1.14832161185134, 1.40363651773545
), IQTe = c(-0.266523341317252, -0.32477349599139, -0.75723700635683,
0.74556355929622, -0.238794158234391, 0.0906173696194765, 0.331200954821995,
-0.373009866084321, 0.417237160703897, 0.755603172535694), PreTe =
c(-0.743400287678305,
-1.1501727014007, -0.668278397501659, -0.0766957410591086, -0.232360222985187,
0.320050787942651, 0.474114337341715, -0.0181639478062117, -0.0905594374421625,
0.517614989060291)), .Names = c("Age", "Gender", "SES", "ISS",
"IQTe", "PreTe"), row.names = c(NA, -10L), class = "data.frame")

u <- runif(10)
[1] 0.72 0.57 0.71 0.64 0.38 0.53 0.14 0.14 0.82 0.12

# Remember two things:
#  (i) ifelse() is a vectorized function;
#  (ii) logical statements return either TRUE (1) or FALSE (0).
#  As a result,

# less efficient:
IAP0 <- ifelse(DataSet$SES > 0, ifelse(u > 0.75, 1, 0),
                                 ifelse(u <= 0.25, 1, 0))
# more efficient:
IAP1 <- ifelse(DataSet$SES > 0, u > 0.75, u <= 0.25) * 1
IAP1
 [1] 0 0 0 0 0 0 1 1 1 0
[1] TRUE

# Verification:
cbind(DataSet$SES, u, IAP1)

This result conforms to what one would expect with u as the realized
uniform random vector. Moreover, the code is transparent: if SES > 0,
then apply the test u > 0.75, else apply the test u <= 0.25). The
post-multiplication by 1 ensures that the result is numeric rather
than logical.

Dennis
On Sat, Feb 2, 2013 at 12:57 PM, soon yi <soon.yi at ymail.com> wrote: