【发布时间】:2018-05-29 16:05:54
【问题描述】:
我有一个两列数据框,其中左列中的值和右列中该值的频率。我想将这些数据反映在一个只有一列的新数据框中。
我已经让它与下面的 2 个 for 循环一起工作,但我的数据(100k+ 行和许多数据帧)非常慢。我尝试过使用 apply 功能,但无法解决。
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)
【问题讨论】:
-
我不会说tidyverse,但你的目标是重复每个
valuecount次吗?然后你可以简单地做rep(twocol$value, twocol$count)
标签: r for-loop tidyverse rbind