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

时间:2021-12-15 20:17:32

I am an beginner in R and have a problem. Any help would really be appreciated! When I apply the for loop in the following (simplified) case, I get an error message saying "replacement has 5 rows, data has 4"

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

Following message given out:

发出以下消息:

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

3 个解决方案

#1


7  

Use ifelse instead

请改用ifelse

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

#2


2  

Check this out:

看一下这个:

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

The i in data$Country syntax iterates through the values in that data.frame attribute. You are then using i as if it is a numerical index. So what you are trying to do is something like this:

数据$ Country语法中的i遍历该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"}}

That being said the above is not idiomatic R, please see @Jilber's answer for a more idiomatic solution.

如上所述,上述不是惯用的R,请参阅@ Jilber的答案,找出更具惯用性的解决方案。

#3


0  

Try:

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

#1


7  

Use ifelse instead

请改用ifelse

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

#2


2  

Check this out:

看一下这个:

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

The i in data$Country syntax iterates through the values in that data.frame attribute. You are then using i as if it is a numerical index. So what you are trying to do is something like this:

数据$ Country语法中的i遍历该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"}}

That being said the above is not idiomatic R, please see @Jilber's answer for a more idiomatic solution.

如上所述,上述不是惯用的R,请参阅@ Jilber的答案,找出更具惯用性的解决方案。

#3


0  

Try:

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