繁体   English   中英

如果在/ R中的/ Else语句

[英]If/Else statement in R

我在R中有两个数据帧:

city         price    bedroom   
San Jose     2000        1          
Barstow      1000        1          
NA           1500        1          

要重新创建的代码:

data = data.frame(city = c('San Jose', 'Barstow'), price = c(2000,1000, 1500), bedroom = c(1,1,1))

和:

Name       Density
San Jose    5358
Barstow      547

要重新创建的代码:

population_density = data.frame(Name=c('San Jose', 'Barstow'), Density=c(5358, 547));

我想根据条件在data集中创建一个名为city_type的附加列,因此如果城市人口密度高于1000,则它是城市,低于1000是郊区,NA是NA。

city         price    bedroom   city_type   
San Jose     2000        1        Urban
Barstow      1000        1        Suburb
NA           1500        1          NA

我正在为条件流使用for循环:

for (row in 1:length(data)) {
    if (is.na(data[row,'city'])) {
        data[row, 'city_type'] = NA
    } else if (population[population$Name == data[row,'city'],]$Density>=1000) {
        data[row, 'city_type'] = 'Urban'
    } else {
        data[row, 'city_type'] = 'Suburb'
   }
}

for循环在原始数据集中运行时没有错误,观察次数超过20000; 然而,它产生了许多错误的结果(它在大多数情况下产生NA)。

这里出了什么问题,我怎样才能更好地达到我想要的结果呢?

对于这种类型的连接/过滤/变异工作流程,我已成为dplyr管道的粉丝。 所以这是我的建议:

library(dplyr)

# I had to add that extra "NA" there, did you not? Hm...
data <- data.frame(city = c('San Jose', 'Barstow', NA), price = c(2000,1000, 500), bedroom = c(1,1,1))
population <- data.frame(Name=c('San Jose', 'Barstow'), Density=c(5358, 547));

data %>% 
  # join the two dataframes by matching up the city name columns
  left_join(population, by = c("city" = "Name")) %>% 
  # add your new column based on the desired condition  
  mutate(
    city_type = ifelse(Density >= 1000, "Urban", "Suburb")
  )

输出:

      city price bedroom Density city_type
1 San Jose  2000       1    5358     Urban
2  Barstow  1000       1     547    Suburb
3     <NA>   500       1      NA      <NA>

使用ifelsepopulation_density创建city_type ,然后我们使用match

population_density$city_type=ifelse(population_density$Density>1000,'Urban','Suburb')
data$city_type=population_density$city_type[match(data$city,population_density$Name)]
data
      city price bedroom city_type
1 San Jose  2000       1     Urban
2  Barstow  1000       1    Suburb
3     <NA>  1500       1      <NA>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM