Ignacio -4 years ago 77
R Question

# How can I write this in a compact efficient way without using a loop?

I know loops should be avoided in R. What is the best way of rewriting this code?

``````X <- structure(list(ELEMENT = c("TMAX", "TMIN", "PRCP", "AWND", "WDF2", "WSF2"),
VALUE1 = c(309L, 249L, 76L, 27L, 110L, 67L),
VALUE2 = c(317L, 274L, 20L, 66L, 110L, 93L),
VALUE3 = c(311L, 266L, 0L, 41L, 120L,57L),
VALUE4 = c(308L, 262L, 0L, 31L, 120L, 57L),
VALUE5 = c(316L, 240L, 0L, 18L, 90L, 41L),
VALUE6 = c(305L, 242L, 51L, 20L, 100L, 36L),
VALUE7 = c(323L, 245L, 0L, 21L, 90L, 41L),
VALUE8 = c(330L, 250L, 287L, 30L, 70L, 62L)),
.Names = c("ELEMENT", "VALUE1", "VALUE2", "VALUE3", "VALUE4",
"VALUE5", "VALUE6", "VALUE7", "VALUE8"),
row.names = 10240:10245, class = "data.frame")

PRCP <- rep(NA, 8)
PRCP[1] <- X[X\$ELEMENT=="PRCP",][[2]]
PRCP[2] <- X[X\$ELEMENT=="PRCP",][[3]]
PRCP[3] <- X[X\$ELEMENT=="PRCP",][[4]]
PRCP[4] <- X[X\$ELEMENT=="PRCP",][[5]]
PRCP[5] <- X[X\$ELEMENT=="PRCP",][[6]]
PRCP[6] <- X[X\$ELEMENT=="PRCP",][[7]]
PRCP[7] <- X[X\$ELEMENT=="PRCP",][[8]]
PRCP[8] <- X[X\$ELEMENT=="PRCP",][[9]]
``````

Thanks!

Answer Source

Is `unlist` what you are looking for?

``````unlist(X[X\$ELEMENT == "PRCP",2:9], use.names=FALSE)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
Latest added