首先生成的數據,名爲 「逸」:
dat <- data.frame(
column1 = runif(n = 638, min=0, max=220),
column2 = runif(n = 638, min=0, max=300),
column3 = runif(n = 638, min=0, max=400),
column4 = runif(n = 638, min=0, max=100),
column5 = runif(n = 638, min=0, max=150),
column6 = runif(n = 638, min=0, max=200))
# define thresholds
threshold1 <- c(16, 22, 31, 6, 11, 13)
threshold2 <- c(200.0, 275.0, 387.5, 75.0, 137.5, 162.5)
使用循環
# Declare a list that will contain the results
results <- list()
# Loop over the columns
for(i in seq_len(ncol(dat))) {
results[[colnames(dat)[i]]] <- ifelse(dat[,i] < threshold1[i],
yes = "speeder",
no = ifelse(dat[,i] > threshold2[i],
yes = "slower", no = 1))
}
使用lapply
你也可以lapply使用,而不是一個循環,像這樣:
results <- lapply(1:ncol(dat), function(x) {
ifelse(dat[,x] < threshold1[x],
yes = "speeder",
no = ifelse(dat[,x] > threshold2[x],
yes = "slower", no = 1))
})
names(results) <- colnames(dat)
結果
,您可以訪問results[[1]]
的結果results[[6]]
或results$column1
到results$column6
> head(results$column1, 100)
[1] "1" "1" "1" "1" "1" "1" "slower"
[8] "1" "slower" "1" "1" "1" "speeder" "1"
[15] "1" "1" "1" "1" "1" "1" "1"
[22] "slower" "1" "1" "1" "1" "1" "1"
[29] "1" "1" "1" "slower" "1" "slower" "slower"
[36] "1" "1" "1" "1" "speeder" "1" "1"
[43] "1" "1" "speeder" "speeder" "1" "1" "slower"
[50] "1" "1" "slower" "1" "1" "1" "1"
[57] "1" "1" "1" "1" "1" "1" "1"
[64] "1" "1" "1" "1" "slower" "1" "1"
[71] "slower" "1" "1" "1" "speeder" "1" "1"
[78] "1" "1" "1" "1" "slower" "1" "1"
[85] "1" "1" "1" "1" "1" "1" "1"
[92] "1" "1" "1" "1" "1" "1" "1"
[99] "speeder" "1"
工作得很好。感謝您的幫助和及時的答覆。 – Miha 2015-03-31 08:15:12
不客氣!不要忘記對最後一起回答的答案加以注意/接受(綠色對號)! :) – 2015-03-31 08:18:29