我知道在R中应该避免循环。重写这段代码的最佳方法是什么?
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]]
谢谢!
答案 0 :(得分:4)
unlist
您要找的是什么?
unlist(X[X$ELEMENT == "PRCP",2:9], use.names=FALSE)
答案 1 :(得分:1)
我会用
as.integer(X[X$ELEMENT == "PRCP",2:9])
或者&#34; as.numeric ...&#34;。 (看起来你想要整数。)这与&#34; unlist&#34;没有什么不同,但这通常就是我做的事。