如何创建带有A列* B列的数据框。
例如,在“年”列(2018年至2025年)中,每年从1:52开始的“周”列中。
基本上,我想要一种更好的方法来获得此结果:
a =data.table( c(2018) , c(1:52))
x <- c("year", "week")
colnames(a) <- x
b =data.table(c(2019) , c(1:52))
x <- c("year", "week")
colnames(b) <- x
c =data.table(c(2020) , c(1:52))
x <- c("year", "week")
colnames(c) <- x
d = rbind(a, b, c)
编辑:谢谢!
答案 0 :(得分:2)
d <- expand.grid(year = c(2018:2020), week = c(1:52))
答案 1 :(得分:2)
使用tidyr
包中的crossing。像这样:
library(tidyr)
library(data.table)
crossing(
data.table(year=2018:2020),
data.table(week=1:52))
有关更多详细信息,请参见https://stackoverflow.com/a/49630818/1358308
答案 2 :(得分:1)
使用基础R
data.frame(year = rep(2018:2020, 52), week = rep(1:52, length(year)))
答案 3 :(得分:1)
由于您似乎使用data.table
,因此这里还有一个选择。
library(data.table)
CJ('year' = 2018:2020, 'week' = 1:52)
# year week
# 1: 2018 1
# 2: 2018 2
# 3: 2018 3
# 4: 2018 4
# 5: 2018 5
# ---
#152: 2020 48
#153: 2020 49
#154: 2020 50
#155: 2020 51
#156: 2020 52
答案 4 :(得分:0)
您只需要致电$collection = User::join('locations as l', 'users.location_id', '=', 'l.id')
->select('users.*', DB::raw('(6371 * acos(cos(radians(' . $coordinates['latitude'] . ')) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(' . $coordinates['longitude'] . ')) + sin(radians(' . $coordinates['latitude'] . ')) * sin(radians(`lat`)))) as distances'))
->having('distances', '<', 32.688888)
->orderBy('distances', 'ASC')
->get();
data.frame
答案 5 :(得分:0)
基本上
year = rep(c(2018:2025),each = 52)
week = rep(c(1:52), length(c(2018:2025)))
d = as.data.frame(cbind(year, week))