我有從1到6000的數字,我希望它以下面列出的方式分開。Reg找到編號IN R編程的範圍和頻率
1-10爲 「範圍1」 10-20爲 「範圍2」 20-30爲 「」 Range3" 。 。 。 5900-6000爲 「範圍600」。
我想計算相等時間間隔的範圍爲10,最後我想計算作爲範圍被重複最多的頻率。
我們如何能一個R編程解決這個問題。
我有從1到6000的數字,我希望它以下面列出的方式分開。Reg找到編號IN R編程的範圍和頻率
1-10爲 「範圍1」 10-20爲 「範圍2」 20-30爲 「」 Range3" 。 。 。 5900-6000爲 「範圍600」。
我想計算相等時間間隔的範圍爲10,最後我想計算作爲範圍被重複最多的頻率。
我們如何能一個R編程解決這個問題。
您應該使用cut
功能然後table
可以確定每個類別中的計數並按照最普遍的順序排序。
x <- 1:6000
x2 <- cut(x, breaks=seq(1,6000,by=10), labels=paste0('Range', 1:599))
sort(table(x2), descending = TRUE)
有一個數學技巧給你的問題。如果你想要長度爲10的類別,round(x/10)將創建一個0-5將變爲0的類別,6到14將變爲1,15到24將變爲2等等。如果要創建cat 1- 10,11-20等,您可以使用round((x + 4.1)/ 10)。
(我不知道爲什麼在r個循環(0.5)= 0,但輪(1.5)= 2,這就是爲什麼我必須使用4.1)
不是最優雅的代碼,但也許是最容易理解的,這裏是一個例子:
# Create randomly 50 numbers between 1 and 60
x = sample(1:60, 50)
# Regroup in a data.frame and had a column count containing the value one for each row
df <- data.frame(x, count=1)
df
# create a new column with the category
df$cat <- round((df$x+4.1)/10)
# If you want it as text:
df$cat2 <- paste("Range",round((df$x+4.1)/10), sep="")
str(df)
# Calculate the number of values in each category
freq <- aggregate(count~cat2, data=df, FUN=sum)
# Get the maximum number of values in the most frequent category(ies)
max(freq$count)
# Get the category(ies) name(s)
freq[freq$count == max(freq$count), "cat2"]
你的意思是5990-6000? – Elin
請提供[輸入示例](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)和預期輸出。 – digEmAll
請參閱''cut''和'?seq' –