我有一个两列的dataframe,它的值在左列,该值的频率在右列。我想在一个只有一列的新数据框中反映这些数据。
我已经让它与下面的2 for循环一起工作,但对于我的数据(100k+行和许多数据帧)来说,它非常慢。我试过使用应用函数,但不能解决这个问题。
library(tidyverse)
twocol <- tribble(
~value, ~count,
0.23076923, 5,
0.69076923, 3,
1.15230769, 4,
1.61384615, 4,
2.15230769, 3
) %>% as.data.frame()
make_onecol <- function(df) {
dfnew <- data.frame(value=NA)
df %>% filter(count!=0) -> df
for (i in 1:nrow(df)) {
n <- df[i, 2]
for (j in 1:n) {
dfnew <- rbind(dfnew, df[i, 1])
}
}
return(dfnew)
}
onecol <- make_onecol(twocol)发布于 2017-12-15 20:34:02
为此,您可以使用rep-function。使用:
onecol <- data.frame(value = c(NA, rep(twocol$value, twocol$count)))提供:
onecol值1 NA 2 0.2307692 3 0.2307692 4 0.2307692 5 0.2307692 6 0.2307692 7 0.6907692 8 0.6907692 9 0.6907692 10 1.1523077 11 1.1523077 12 1.1523077 13 1.1523077 14 1.6138462 16 1.6138462 17 1.6138462 18 2.1523077 19 2.1523077 20 2.1523077
发布于 2017-12-15 20:33:59
使用data.table的rep包装器
library(data.table)
setDT(twocol)[, .(value = rep(value, count))]
# value
# 0.2307692
# 0.2307692
# 0.2307692
# 0.2307692
# 0.2307692
# 0.6907692
# 0.6907692
# 0.6907692
# 1.1523077
# 1.1523077
# 1.1523077
# 1.1523077
# ...https://stackoverflow.com/questions/47832460
复制相似问题