gpt4 book ai didi

r - For 循环 : replacement has one row more than data

转载 作者:行者123 更新时间:2023-12-04 11:54:32 28 4
gpt4 key购买 nike

我是 R 的初学者,遇到了问题。任何帮助将不胜感激!
当我在以下(简化的)情况下应用 for 循环时,我收到一条错误消息,指出“替换有 5 行,数据有 4”

Country <- c("Germany", "France", "Italy", "Spain")
Unemploy <- c(2, 3, 4, 10)
Growth <- c(2, 7, 6, 9)
data <- data.frame(Country, Unemploy, Growth)

for (i in data$Country) {
if (identical(data$Country[i], "France")) {
data$Growth[i] <- "5"
} else {
data$Growth[i] <- "2"
}
}

发出以下消息:
Error in `$<-.data.frame`(`*tmp*`, "Growth", value = c("2", "2", "2",  : 
replacement has 5 rows, data has 4

最佳答案

使用 ifelse反而

data[ ,"Growth"] <- ifelse(data[ , "Country"] == "France", "5", "2")

关于r - For 循环 : replacement has one row more than data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20435157/

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