gpt4 book ai didi

r - 在 R 中解析数据帧以查找值频率的更快方法?

转载 作者:行者123 更新时间:2023-12-02 20:28:59 25 4
gpt4 key购买 nike

我在 R 中有一个数据帧,其中包含一列距离(第 12 列)以及该距离是否存在匹配项(第 13 列)。 1 代表匹配,0 代表不匹配。例如:

distance    match
1 0
1 1
1 1
2 1
2 0
3 1
4 0
4 0

我想找到每个距离值的频率,并找到每个值的匹配百分比。

例如,对于上面的表格,我想要得到这样的东西:

distance    frequency    matches
1 3 2
2 2 1
3 1 1
4 2 0

我当前的代码如下所示:

  #Create a new list with unique distance values
distance <- unique(methyl_data[,12])

#Count how many of each distance and how many matches there are
total = c()
matches = c()

dl = length(distance)
ml = length(methyl_data[,12])

match = FALSE
tcounter = 0
mcounter = 0
for (d in 1:dl) {
for (x in 1:ml){
if (distance[d] == methyl_data[x, 12]) {
match = TRUE
tcounter <- tcounter + 1
if (methyl_data[x, 13] == 1) {
mcounter <- mcounter + 1
}
}

#Add the frequency and number of matches for the last data entry
if(d== dl && x ==ml) {
total = c(total, tcounter)
matches = c(matches, mcounter)
}
if((distance[d] != methyl_data[x, 12]) && match == TRUE) {
match = FALSE
total = c(total, tcounter)
matches = c(matches, mcounter)
tcounter =0
mcounter =0
}

}



}

View(distance)
#Create a table with the frequency of distances and matches and percentage of matches
percentage = (matches/total)
table = cbind(distance, total, matches, percentage)

但是,该数据帧有近 200 万行,因此该循环效率低下。有没有内置的 R 函数可以简化我的代码?我的最终目标是查看距离和匹配之间是否存在关系,那么对于非常大的数据集是否有更简单的方法来做到这一点?

提前致谢。

最佳答案

有多种方法可以做到这一点。

方法1:使用dplyr包:

library(dplyr)
df %>%
group_by(distance) %>%
mutate(frequency = n(), matches = sum(match)) %>%
select(distance, frequency, matches) %>%
distinct()

print(df)

distance frequency matches
<int> <int> <int>
1 1 3 2
2 2 2 1
3 3 1 1
4 4 2 0

方法2:使用data.table包(如果您的数据量很大,则首选此方法)

library(data.table)
setDT(df)
df[,':='(frequency = .N, matches = sum(match)), .(distance)]
df <- unique(df[,.(distance, frequency, matches)])

print(df)
distance frequency matches
1: 1 3 2
2: 2 2 1
3: 3 1 1
4: 4 2 0

关于r - 在 R 中解析数据帧以查找值频率的更快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49328843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com