For循环:替换比数据多一行

时间:2013-12-06 23:03:43

标签: r for-loop

我是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

3 个答案:

答案 0 :(得分:7)

使用ifelse代替

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

答案 1 :(得分:2)

检查出来:

> for (i in data$Country){print(i)}
[1] "Germany"
[1] "France"
[1] "Italy"
[1] "Spain"

i in data$Country语法遍历该data.frame属性中的值。然后,您使用i,就好像它是一个数字索引。所以你要做的就是这样:

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

如上所述,上述内容并非惯用R,请参阅@ Jilber的答案以获得更为惯用的解决方案。

答案 2 :(得分:0)

尝试:

for (i in 1:length(data$Country)) {
    ...