我有一个包含2列的数据框A,即“Amount”和“Number of times”。我想创建一个新的数据帧B,它根据“次数”重复数据帧A中的“数量”。例如,如果数据框A中的第一行具有“Ammount”= 50且“次数”= 4且第二行具有“Amount”= 80且“Number of times”= 2,则我想创建新的数据帧B如下图所示:
50 50 50 50
80 80
因此,数据帧B的行将具有不同的长度。请帮忙!
答案 0 :(得分:0)
以下是使用do {
$body->reportRequests[0]->setPageToken($token);
$data = $analytics->reports->batchGet( $body );
$token = $data->reports[0]->getNextPageToken();
$this->printResults($data);
} while ( $token != '' );
执行此操作的一种方法:
apply
这是一个不那么罗嗦的替代方案:
A <- data.frame(Amount = c(50, 80), Times = c(4, 2))
# Amount Times
# 1 50 4
# 2 80 2
x <- apply(A, 1, function(r) {
c(rep(r[['Amount']], r['Times']), rep(NA, max(A['Times'] - r['Times'])))
})
t(x)
# [,1] [,2] [,3] [,4]
# [1,] 50 50 50 50
# [2,] 80 80 NA NA
答案 1 :(得分:0)
选项#1:强>
使用splitstackshape::cSplit
包的选项:
df <- data.frame(Amt = c(50, 80), NoTime = c(4,2))
library(splitstackshape)
df_B <- data.frame(col = apply(df, 1, function(x)paste(rep(x[1],x[2]),collapse = ",")))
cSplit(df_B, "col", sep = ",")
# col_1 col_2 col_3 col_4
# 1: 50 50 50 50
# 2: 80 80 NA NA
选项#2:基于tidyverse
的解决方案可以是:
library(tidyverse)
df$rn <- 1:nrow(df)
df_B <- df[rep(seq(nrow(df)), df$NoTime),]
df_B %>% select(-NoTime) %>%
group_by(rn) %>%
mutate(rowN = row_number()) %>%
spread(rowN, Amt)
# # A tibble: 2 x 5
# # Groups: rn [2]
# rn `1` `2` `3` `4`
# * <int> <dbl> <dbl> <dbl> <dbl>
# 1 1 50.0 50.0 50.0 50.0
# 2 2 80.0 80.0 NA NA