For a loop: a replacement has one row larger than the data

I am new to R and have a problem. Any help would be really appreciated! When I use the for loop in the following (simplified) case, I get the error message: "replacement has 5 lines, data has 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" } } 

The following message is displayed:

 Error in `$<-.data.frame`(`*tmp*`, "Growth", value = c("2", "2", "2", : replacement has 5 rows, data has 4 
+6
source share
3 answers

Use ifelse instead

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

Check this:

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

Syntax i in data$Country iterates through the values ​​in this data.frame attribute. Then you use i as if it is a numeric index. So what you are trying to do is something like this:

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

The above is not an idiomatic R, see @Jilber's answer for a more idiomatic solution.

+2
source

Try:

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

Source: https://habr.com/ru/post/959504/


All Articles