分配给data.frame时,向量回收不起作用

分配给data.frame时,向量回收不起作用,r,R,我指望vector recycling用模拟数据填充R数据帧,但其行为与预期不符 我可以成功地运行此功能: store.df <- data.frame(matrix(NA, ncol=5, nrow=2080)) names(store.df)<-c("storeNum", "upc_id", "Week_id", "weekday_id", "units") sn<-c(60, 89, 105, 170, 1240) store.df$storeNum <- sn w

我指望vector recycling用模拟数据填充R数据帧,但其行为与预期不符

我可以成功地运行此功能:

store.df <- data.frame(matrix(NA, ncol=5, nrow=2080))
names(store.df)<-c("storeNum", "upc_id", "Week_id", "weekday_id", "units")
sn<-c(60, 89, 105, 170, 1240)
store.df$storeNum <- sn
wid<-c(201531,201532,201533,201534,201535,201536,201537,201538)
store.df$Week_id <- wid
但是,如果我使用这里看到的最后两行:

store.df <- data.frame(matrix(NA, ncol=5, nrow=2080))
names(store.df)<-c("storeNum", "upc_id", "Week_id", "weekday_id", "units")
sn<-c(60, 89, 105, 170, 1240)
store.df$storeNum <- sn
wid<-c(201531,201532,201533,201534,201535,201536,201537,201538)
store.df$Week_id <- wid
wdid<-c(1,2,3,4,5,6,7)
store.df$weekday_id <- wdid

这是因为2000不能被7整除。部分回收不适用于数据框列:

d <- data.frame(x=1:10)
d$x <- 1
d$x <- 1:2
d$x <- 1:3
# Error in `$<-.data.frame`(`*tmp*`, "x", value = 1:3) : 
#  replacement has 3 rows, data has 10
您可以类似地对数据帧进行赋值(如果您确定这是您想要做的):


d$x[]谢谢你。”store.df$weekday_id[]
wdid<-c(1,2,3,4,5,6,7)
store.df$weekday_id <- wdid
Error in `$<-.data.frame`(`*tmp*`, "weekday_id", value = c(1, 2, 3, 4,  : 
  replacement has 7 rows, data has 2080
d <- data.frame(x=1:10)
d$x <- 1
d$x <- 1:2
d$x <- 1:3
# Error in `$<-.data.frame`(`*tmp*`, "x", value = 1:3) : 
#  replacement has 3 rows, data has 10
x <- d$x
x[] <- 1:3
# Warning message:
# In x[] <- 1:3 :
#   number of items to replace is not a multiple of replacement length

x
# [1] 1 2 3 1 2 3 1 2 3 1
d$x[] <- 1:3
# Warning message:
# In d$x[] <- 1:3 :
#   number of items to replace is not a multiple of replacement length
d
#    x
# 1  1
# 2  2
# 3  3
# 4  1
# 5  2
# 6  3
# 7  1
# 8  2
# 9  3
# 10 1