gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:13:55 26 4
gpt4 key购买 nike

我希望通过向量回收来用模拟数据填充 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

要实现这一点:

summary(store.df)

storeNum upc_id Week_id weekday_id units
Min. : 60.0 Mode:logical Min. :201531 Mode:logical Mode:logical
1st Qu.: 89.0 NA's:2080 1st Qu.:201533 NA's:2080 NA's:2080
Median : 105.0 Median :201535
Mean : 332.8 Mean :201535
3rd Qu.: 170.0 3rd Qu.:201536
Max. :1240.0 Max. :201538

但是,如果我运行此处看到的最后两行:

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

然后我收到此错误:

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

为什么我不能回收 wdid矢量成store.df与我在前两个语句( store.df$storeNum <- snstore.df$Week_id <- wid )中获得的成功相同?

是否可以在不转换的情况下成功 wdid到与 store.df 长度相同的向量?

最佳答案

这是因为 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

来自相关帮助文本? [<-.data.frame ,在参数部分:

"value :合适的替换值:如有必要,它将重复全部次"

部分回收对向量有效:

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

关于r - 分配给 data.frame 时向量回收不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34984537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com