매트릭스의 각 셀마다 몇 가지 가능성이 있습니까? 그것은 당신의 모범과 똑같은가요? 당신은 넥타이가있는 경우, 모든 컬럼의 이름을 얻고 싶다면 예 다음과 같은 것이
dat <- structure(c("blue", "green", "yellow", "red", "blue", "green",
"red", "red", "red", "red", "red", "red", "red", "red", "blue",
"blue", "blue", "blue", "green", "green", "red", "blue", "blue",
"blue", "blue", "blue", "blue", "red", "blue", "blue", "blue",
"blue", "blue", "blue", "blue", "red", "red", "red", "red", "red",
"red", "blue", "green", "green", "green", "green", "green", "green",
"blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue",
"blue", "blue", "blue", "blue", "blue", "blue", "green"), .Dim = c(7L,
9L))
values <- c("blue", "red", "green", "yellow")
counts <- vapply(values, function(value) rowSums(dat == value),
numeric(nrow(dat))) # Thanks to @RichardScriven for the improvement :)
counts
# blue red green yellow
# [1,] 6 2 1 0
# [2,] 5 2 2 0
# [3,] 5 2 1 1
# [4,] 5 3 1 0
# [5,] 5 2 2 0
# [6,] 4 2 3 0
# [7,] 4 4 1 0
max.value.col <- max.col(counts)
max.value <- colnames(counts)[max.value.col]
max.counts <- counts[cbind(1:nrow(counts), max.value.col)]
paste(max.value, max.counts, sep = ", ")
# [1] "blue, 6" "blue, 5" "blue, 5" "blue, 5" "blue, 5" "blue, 4"
빠를 수 있습니다 경우 다음 작동 것이지만, apply
의 성능에 대해 확실하지 잠시 (이 걸릴 수 있습니다 이 경우)
max.value.all.cols <- counts == counts[cbind(1:nrow(counts), max.value.col)]
paste(
apply(max.value.all.cols, 1, function(r) paste(paste(colnames(counts)[r],
collapse = ", "))),
max.counts, sep = ", ")
당신이 현재 비교 사용하고있는 코드를 보여줄 수 :
나는 다른 사람과 같은 데이터를 사용? –"너무 오래"얼마나 걸립니까? 얼마나 빨리이 작업이 필요합니까? 당신이 그걸 대답 할 수 없다면 나는 당신이 얼마나 오래 "너무 길다"고 말할 수 있다고 생각하지 않는다. – Spacedman
누군가가 엄청나게 속도가 빨라진 솔루션을 게시했지만 코드는 40 초 정도 실행되었습니다. 해결책은 약 1 초 정도 걸리므로 완벽합니다 :-). – user1357015