【发布时间】:2021-12-29 03:48:00
【问题描述】:
我有一个包含 1600 万行的数据框,我希望在现有列 Month 的基础上添加一列。如果月份是 3 或 4 或 5,列 Season 将为 spring 等。
for (i in 1:nrow(df)) {
if (df$Month[[i]] %in% c(3,4,5)) {
df$Season[[i]] <- "Spring"
} else if (df$Month[[i]] %in% c(6,7,8)) {
df$Season[[i]] <- "Summer"
} else if (df$Month[[i]] %in% c(9,10,11)) {
df$Season[[i]] <- "Autumn"
} else if (df$Month[[i]] %in% c(12,1,2)) {
df$Season[[i]] <- "Winter"
}
}
但是,它需要很长时间才能完成。我能做什么?
【问题讨论】:
-
对于这么大的数据帧,尽量不要使用 for 循环。总有一个矢量化的替代方案。
标签: r